Source类:Layer的重要组成部分,表示图层的来源,也就是服务地址。除了在构造函数中制定外,可以使用 layer.setSource(source)
稍后指定。
@typedef {string|Array<string>|Attribution} AttributionLike
/**
* @typedef {Object} Options
* @property {AttributionLike} [attributions] Attributions.
* @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.
* @property {import("../proj.js").ProjectionLike} [projection] Projection. Default is the view projection.
* @property {import("./Source.js").State} [state='ready'] State.
* @property {boolean} [wrapX=false] WrapX.
* @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,
* the nearest neighbor is used when resampling.
*/
class Source extends BaseObject {
/**
* @param {Options} options Source options.
*/
constructor(options) {
super();
... ...
父类:BaseObject
构造函数参数:自定义类型Options,其类型为Object对象。包含6种属性(被其子类选择性继承):
property name | type | Description |
attributions | AttributionLike | undefined | 地图右下角的 logo 包含的内容 |
attributionsCollapsible | boolean (defaults to true) | Attributions是否折叠 |
projection | ProjectionLike | undefined | 投影 |
state | State (defaults to 'ready') | 地图所处的状态 |
wrapX | boolean (defaults to false) | 是否在地图水平坐标轴上重复,默认是 true 。 |
interpolate | boolean (defaults to false) | 重采样时使用插值值。 缺省情况下,重采样时使用最近的邻居。 |
事件:
change
(BaseEvent) - 当修订计数器增加时触发。error
(BaseEvent) -发生错误时触发。propertychange
(ObjectEvent) -当更改属性时触发。
1、VectorSource:矢量图层的数据来源
参数:
Name | Type | Description |
---|---|---|
attributions | AttributionLike | undefined | 地图右下角的 logo 包含的内容 |
features | Array<Feature> | Collection<Feature> | undefined | 地理要素,从字符串读取的数据 |
format | FeatureFormat | undefined | url属性设置后,加载要素使用的数据格式,采用异步的 AJAX 加载; |
loader | FeatureLoader | undefined | 没有设置url属性,加载url要素使用的加载函数; |
overlaps | boolean (defaults to true) | 这个源可能有重叠的几何图形。 设置为false允许渲染器优化填充和笔画操作。 |
strategy | LoadingStrategy | undefined | 加载要素使用的策略,默认是 一次性加载所有要素; |
url | string | FeatureUrlFunction | undefined | 要素数据的地址 |
useSpatialIndex | boolean (defaults to true) | 默认情况下,使用RTree作为空间索引。 当特性被频繁地删除和添加,并且特性的总数很低时,将其设置为false可能会提高性能。 |
wrapX | boolean (defaults to true) | 是否在地图水平坐标轴上重复,默认是 true 。 |
事件类型:
addfeature
(VectorSourceEvent) - 当一个要素添加到 source 中触发;change
(BaseEvent) - 当修订计数器增加时触发。(继承)changefeature
(VectorSourceEvent) - 当要素变化时触发;clear
(VectorSourceEvent) - 当 source 的 clear 方法调用时候触发;error
(BaseEvent) - 发生错误时触发;(继承)featuresloadend
(VectorSourceEvent) - Triggered when features finishes loading.featuresloaderror
(VectorSourceEvent) - Triggered if feature loading results in an error.featuresloadstart
(VectorSourceEvent) - Triggered when features starts loading.propertychange
(ObjectEvent) - 当更改属性时触发;(继承)removefeature
(VectorSourceEvent) - 当要素移除时候发生。
实例:
1)loader+format方法( If this is not set and url
is set, the source will create and use an XHR feature loader. ):
import {Vector} from 'ol/source';
import {GeoJSON} from 'ol/format';
import {bbox} from 'ol/loadingstrategy';
const vectorSource = new Vector({
format: new GeoJSON(),
loader: function(extent, resolution, projection, success, failure) {
const proj = projection.getCode();
const url = 'https://ahocevar.com/geoserver/wfs?service=WFS&' +
'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +
'outputFormat=application/json&srsname=' + proj + '&' +
'bbox=' + extent.join(',') + ',' + proj;
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
const onError = function() {
vectorSource.removeLoadedExtent(extent);
failure();
}
xhr.onerror = onError;
xhr.onload = function() {
if (xhr.status == 200) {
const features = vectorSource.getFormat().readFeatures(xhr.responseText);
vectorSource.addFeatures(features);
success(features);
} else {
onError();
}
}
xhr.send();
},
strategy: bbox,
});
2)features 方法
//import {Vector} from 'ol/source';
//import {GeoJSON} from 'ol/format';
var vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: style
});
map.addLayer(vectorLayer);
3)url + format 方法
//import VectorLayer from 'ol/layer/Vector';
var vectorLayer = new ol.layer.Vector({
source: new ol.source.Vector({
url: 'data/geojson/countries.geojson',
format: new ol.format.GeoJSON()
})
});
1)3)两种方法中都会指定数据来源format, 矢量数据源支持的格式包含很多:gml、EsriJSON、geojson、gpx、igc、kml、osmxml、ows、polyline、topojson、wfs、wkt、wms capabilities(兼容 wms 的格式)、 wms getfeatureinfo、 wmts capabilities、xlink、xsd等格式。这些格式都有readFeatures 、readFeature 和readGeometry 方法用于读取数据。
2、TileSource:提供被切分为切片的图片地图数据
XYZ:
参数:
Name | Type | Description |
---|---|---|
attributions | AttributionLike | undefined | 地图右下角的 logo 包含的内容 |
attributionsCollapsible | boolean (defaults to true) | Attributions是否折叠 |
cacheSize | number | undefined | 初始贴图缓存大小。 |
crossOrigin | null | string | undefined | 加载图片的crossOrigin属性。 注意,如果你想用Canvas渲染器访问像素数据,你必须提供一个跨源值。 |
interpolate | boolean (defaults to true) | 重采样时使用插值值。默认情况下,重采样时使用线性插值。设置为false则使用最近的邻居。 |
opaque | boolean (defaults to false) | 层是否不透明。 |
projection | ProjectionLike (defaults to 'EPSG:3857') | 投影 |
reprojectionErrorThreshold | number (defaults to 0.5) | 是否允许最大重投影误差(像素)。 较高的值可以提高重投影性能,但会降低精度。 |
maxZoom | number (defaults to 42) | 可选最大缩放级别。 如果提供了tileGrid则不使用。 |
minZoom | number (defaults to 0) | Optional min zoom level. Not used if |
maxResolution | number | undefined | 可选的瓷砖网格分辨率为零级。如果提供了tileGrid则不使用。 |
tileGrid | TileGrid | undefined | Tile grid. |
tileLoadFunction | LoadFunction | undefined | 可选的函数,加载给定URL的贴图. The default is |
tilePixelRatio | number (defaults to 1) | 贴图服务使用的像素比率。 例如,如果贴图服务宣传的是256px * 256px的贴图,但实际上发送的是512px * 512px的图像(针对retina/hidpi设备),那么tilePixelRatio就应该设置为2。 |
tileSize | number | Size (defaults to [256, 256]) | 瓷砖服务使用的瓷砖大小。 如果提供了tileGrid则不使用。 |
gutter | number (defaults to 0) | The size in pixels of the gutter around image tiles to ignore. This allows artifacts of rendering at tile edges to be ignored. Supported images should be wider and taller than the tile size by a value of |
tileUrlFunction | UrlFunction | undefined | Optional function to get tile URL given a tile coordinate and the projection. Required if |
url | string | undefined | URL template. Must include |
urls | Array.<string> | undefined | An array of URL templates. |
wrapX | boolean (defaults to true) | Whether to wrap the world horizontally. |
transition | number (defaults to 250) | Duration of the opacity transition for rendering. To disable the opacity transition, pass |
zDirection | number | NearestDirectionFunction (defaults to 0) | Choose whether to use tiles with a higher or lower zoom level when between integer zoom levels. See getZForResolution. |
事件类型:
Fires:
change
(BaseEvent) - Generic change event. Triggered when the revision counter is increased.error
(BaseEvent) - Generic error event. Triggered when an error occurs.propertychange
(ObjectEvent) - Triggered when a property is changed.tileloadend
(TileSourceEvent) - 当一个贴图完成加载时触发,或者当它的数据被加载,或者当加载被中止,因为这个贴图不再需要。tileloaderror
(TileSourceEvent) -当贴图加载导致错误则触发。tileloadstart
(TileSourceEvent) - 当一个贴图开始加载时触发。
方法:
on(type(事件类型), listener(监听回调)) Listen for a certain type of event.
返回{EventsKey | Array<EventsKey>}
实例:
const key = 'get_your_own_D6rA4zTHduk6KOKTXzGB';
const attributions =
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>';
const source = new XYZ({
attributions: attributions,
url: 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=' + key,
tileSize: 512,
});
const map = new Map({
layers: [new TileLayer({source: source})],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
openlayers官方实例:Tile Load Events (openlayers.org) 实现加载进度条
GeoTIFF:
实例:
const layer = new TileLayer({
style: trueColor,
source: new GeoTIFF({
normalize: false,
sources: [
{
url: 'https://s2downloads.eox.at/demo/EOxCloudless/2020/rgbnir/s2cloudless2020-16bits_sinlge-file_z0-4.tif',
},
],
}),
});
const map = new Map({
target: 'map',
layers: [layer],
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 2,
maxZoom: 6,
}),
});
WMTS:
Name | Type | Description |
---|---|---|
attributions | AttributionLike | undefined | Attributions. |
attributionsCollapsible | boolean (defaults to true) | Attributions are collapsible. |
cacheSize | number | undefined | Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport. |
crossOrigin | null | string | undefined | The |
interpolate | boolean (defaults to true) | Use interpolated values when resampling. By default, linear interpolation is used when resampling. Set to false to use the nearest neighbor instead. |
tileGrid | WMTSTileGrid | Tile grid. |
projection | ProjectionLike | undefined | Projection. Default is the view projection. |
reprojectionErrorThreshold | number (defaults to 0.5) | Maximum allowed reprojection error (in pixels). Higher values can increase reprojection performance, but decrease precision. |
requestEncoding | RequestEncoding (defaults to 'KVP') | Request encoding. |
layer | string | 在WMTS功能中发布的层名称。 |
style | string | Style name as advertised in the WMTS capabilities. |
tileClass | Class<ImageTile> | undefined | Class used to instantiate image tiles. Default is ImageTile. |
tilePixelRatio | number (defaults to 1) | The pixel ratio used by the tile service. For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px by 512px images (for retina/hidpi devices) then |
format | string (defaults to 'image/jpeg') | Image format. Only used when |
version | string (defaults to '1.0.0') | WMTS version. |
matrixSet | string | 矩阵集 |
dimensions | Object | undefined | tile请求的额外“维度”。这是一个具有与所宣传的WMTS维类似的属性的对象。 |
url | string | undefined | A URL for the service. For the RESTful request encoding, this is a URL template. For KVP encoding, it is normal URL. A |
tileLoadFunction | LoadFunction | undefined | Optional function to load a tile given a URL. The default is |
urls | Array.<string> | undefined | An array of URLs. Requests will be distributed among the URLs in this array. |
wrapX | boolean (defaults to false) | Whether to wrap the world horizontally. |
transition | number | undefined | Duration of the opacity transition for rendering. To disable the opacity transition, pass |
zDirection | number | NearestDirectionFunction (defaults to 0) | Choose whether to use tiles with a higher or lower zoom level when between integer zoom levels. See getZForResolution. |
实例:
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
import WMTS from 'ol/source/WMTS';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import {get as getProjection} from 'ol/proj';
import {getTopLeft, getWidth} from 'ol/extent';
// create the WMTS tile grid in the google projection。创建瓦片
const projection = getProjection('EPSG:3857');
//最低分辨率的瓦片数量
const tileSizePixels = 256;
//最低分辨率的瓦片宽度
const tileSizeMtrs = getWidth(projection.getExtent()) / tileSizePixels;
const matrixIds = [];
const resolutions = [];
for (let i = 0; i <= 14; i++) {
//第i分辨率
matrixIds[i] = i;
//四叉树。每个分辨率数组中的瓦片的宽度
resolutions[i] = tileSizeMtrs / Math.pow(2, i);
}
const tileGrid = new WMTSTileGrid({
origin: getTopLeft(projection.getExtent()),
resolutions: resolutions,
matrixIds: matrixIds,
});
const scalgoToken = 'CC5BF28A7D96B320C7DFBFD1236B5BEB';
const wmtsSource = new WMTS({
url: 'https://ts2.scalgo.com/olpatch/wmts?token=' + scalgoToken,
layer: 'SRTM_4_1:SRTM_4_1_flooded_sealevels',
format: 'image/png',
matrixSet: 'EPSG:3857',
attributions: [
'<a href="https://scalgo.com" target="_blank">SCALGO</a>',
'<a href="https://cgiarcsi.community/data/' +
'srtm-90m-digital-elevation-database-v4-1"' +
' target="_blank">CGIAR-CSI SRTM</a>',
],
tileGrid: tileGrid,
style: 'default',
dimensions: {
'threshold': 100,
},
});
const map = new Map({
target: 'map',
view: new View({
projection: projection,
center: [-9871995, 3566245],
zoom: 6,
}),
layers: [
new TileLayer({
source: new OSM(),
}),
new TileLayer({
opacity: 0.5,
source: wmtsSource,
}),
],
});
UTFGrid:
Name | Type | Description |
---|---|---|
preemptive | boolean (defaults to true) | If |
jsonp | boolean (defaults to false) | Use JSONP with callback to load the TileJSON. Useful when the server does not support CORS.. |
tileJSON | Config | undefined | 此源的TileJSON配置。如果没有提供,则必须配置url。 |
url | string | undefined | 提供此源配置的TileJSON url。如果没有提供,则必须配置tileJSON。 |
zDirection | number | NearestDirectionFunction (defaults to 0) | Choose whether to use tiles with a higher or lower zoom level when between integer zoom levels. See getZForResolution. |
方法:
forDataAtCoordinateAndResolution(coordinate, resolution, callback, request)
根据坐标和分辨率获取tilejson数据传给回调函数callback
3、ImageSource: 提供单个图像的源的基类。
ImageWMS
参数:
Name | Type | Description |
---|---|---|
attributions | AttributionLike | undefined | Attributions. |
crossOrigin | null | string | undefined | The |
hidpi | boolean (defaults to true) | Use the |
serverType | ServerType | undefined | The type of the remote WMS server: |
imageLoadFunction | LoadFunction | undefined | Optional function to load an image given a URL. |
interpolate | boolean (defaults to true) | Use interpolated values when resampling. By default, linear interpolation is used when resampling. Set to false to use the nearest neighbor instead. |
params | Object.<string, *> | undefined | WMS请求参数(见WMS标准)。 至少需要一个LAYERS参数 |
projection | ProjectionLike | undefined | Projection. Default is the view projection. |
ratio | number (defaults to 1.5) | 比率。1表示图像请求是地图视口的大小,2表示地图视口大小的两倍,以此类推。 |
resolutions | Array.<number> | undefined | Resolutions. If specified, requests will be made for these resolutions only. |
url | string | undefined | WMS service URL. |
实例:
//一个切片图层一个WMS影像图层
const layers = [
new TileLayer({
source: new OSM(),
}),
new ImageLayer({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ImageWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states'},
ratio: 1,
serverType: 'geoserver',
}),
}),
];
const map = new Map({
layers: layers,
target: 'map',
view: new View({
center: [-10997148, 4569099],
zoom: 4,
}),
});
ImageArcGISRest:
参数:
Name | Type | Description |
---|---|---|
attributions | AttributionLike | undefined | Attributions. |
crossOrigin | null | string | undefined | The |
hidpi | boolean (defaults to true) | Use the |
imageLoadFunction | LoadFunction | undefined | Optional function to load an image given a URL. |
interpolate | boolean (defaults to true) | Use interpolated values when resampling. By default, linear interpolation is used when resampling. Set to false to use the nearest neighbor instead. |
params | Object.<string, *> | undefined | ArcGIS Rest parameters. This field is optional. Service defaults will be used for any fields not specified. |
projection | ProjectionLike | undefined | Projection. Default is the view projection. The projection code must contain a numeric end portion separated by : or the entire code must form a valid ArcGIS SpatialReference definition. |
ratio | number (defaults to 1.5) | Ratio. |
resolutions | Array.<number> | undefined | Resolutions. If specified, requests will be made for these resolutions only. |
url | string | undefined | ArcGIS Rest service URL for a Map Service or Image Service. The url should include /MapServer or /ImageServer. |
实例:
const url =
'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' +
'Specialty/ESRI_StateCityHighway_USA/MapServer';
const layers = [
new TileLayer({
source: new OSM(),
}),
new ImageLayer({
source: new ImageArcGISRest({
ratio: 1,
params: {},
url: url,
}),
}),
];
const map = new Map({
layers: layers,
target: 'map',
view: new View({
center: [-10997148, 4569099],
zoom: 4,
}),
});
ImageCanvasSource
这个类用于高效绘制大量矢量要素,ol官网没有相关实例,后期再深入学习。
OPENLAYERS 6 通过在OL.SOURCE.IMAGECANVAS中获取VECTORCONTEXT对象高效率绘制海量要素(支持点、线、面)
ImageMapGuide:加载mapguide server的地图,不常用
static:
参数:
Name | Type | Description |
---|---|---|
attributions | AttributionLike | undefined | Attributions. |
crossOrigin | null | string | undefined | The |
imageExtent | Extent | undefined | 图像在地图坐标中的范围。 这是图像的[左,下,右,上]地图坐标。 |
imageLoadFunction | LoadFunction | undefined | Optional function to load an image given a URL. |
interpolate | boolean (defaults to true) | Use interpolated values when resampling. By default, linear interpolation is used when resampling. Set to false to use the nearest neighbor instead. |
projection | ProjectionLike | undefined | Projection. Default is the view projection. |
imageSize | Size | undefined | Size of the image in pixels. Usually the image size is auto-detected, so this only needs to be set if auto-detection fails for some reason. |
url | string | Image URL. |
实例:
const extent = [0, 0, 1024, 968];
const projection = new Projection({
code: 'xkcd-image',
units: 'pixels',
extent: extent,
});
const map = new Map({
layers: [
new ImageLayer({
source: new Static({
attributions: '© <a href="https://xkcd.com/license.html">xkcd</a>',
url: 'https://imgs.xkcd.com/comics/online_communities.png',
projection: projection,
imageExtent: extent,
}),
}),
],
target: 'map',
view: new View({
projection: projection,
center: getCenter(extent),
zoom: 2,
maxZoom: 8,
}),
});
RasterSource:
参数
Name | Type | Description |
---|---|---|
sources | Array.<(module:ol/source/Source~Source|module:ol/layer/Layer~Layer)> | Input sources or layers. For vector data, use an VectorImage layer. |
operation | Operation | undefined | Raster operation. The operation will be called with data from input sources and the output will be assigned to the raster source. |
lib | Object | undefined | 在operation中用到的一些函数 |
threads | number | undefined | By default, operations will be run in a single worker thread. To avoid using workers altogether, set |
operationType | RasterOperationType (defaults to 'pixel') | Operation type. Supported values are |