ol7源码学习之Source

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 nametypeDescription
attributionsAttributionLike | undefined地图右下角的 logo 包含的内容
attributionsCollapsibleboolean (defaults to true)

Attributions是否折叠

projectionProjectionLike | undefined投影
stateState (defaults to 'ready')地图所处的状态
wrapXboolean (defaults to false)是否在地图水平坐标轴上重复,默认是 true
interpolateboolean (defaults to false)重采样时使用插值值。 缺省情况下,重采样时使用最近的邻居。 

 事件:

1、VectorSource:矢量图层的数据来源

参数:

NameTypeDescription
attributionsAttributionLike | undefined地图右下角的 logo 包含的内容
featuresArray<Feature> | Collection<Feature> | undefined

地理要素,从字符串读取的数据

formatFeatureFormat | undefined

url属性设置后,加载要素使用的数据格式,采用异步的 AJAX 加载;

loaderFeatureLoader | undefined

没有设置url属性,加载url要素使用的加载函数;

overlapsboolean (defaults to true)这个源可能有重叠的几何图形。 设置为false允许渲染器优化填充和笔画操作。 
strategyLoadingStrategy | undefined加载要素使用的策略,默认是 一次性加载所有要素;
urlstring | FeatureUrlFunction | undefined

要素数据的地址

useSpatialIndexboolean (defaults to true)默认情况下,使用RTree作为空间索引。 当特性被频繁地删除和添加,并且特性的总数很低时,将其设置为false可能会提高性能。  
wrapXboolean (defaults to true)是否在地图水平坐标轴上重复,默认是 true

事件类型:

实例:

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:

参数:

NameTypeDescription
attributionsAttributionLike | undefined地图右下角的 logo 包含的内容
attributionsCollapsibleboolean (defaults to true)Attributions是否折叠
cacheSizenumber | undefined初始贴图缓存大小。
crossOriginnull | string | undefined加载图片的crossOrigin属性。 注意,如果你想用Canvas渲染器访问像素数据,你必须提供一个跨源值。 
interpolateboolean (defaults to true)重采样时使用插值值。默认情况下,重采样时使用线性插值。设置为false则使用最近的邻居。
opaqueboolean (defaults to false)层是否不透明。
projectionProjectionLike (defaults to 'EPSG:3857')

投影

reprojectionErrorThresholdnumber (defaults to 0.5)是否允许最大重投影误差(像素)。 较高的值可以提高重投影性能,但会降低精度。
maxZoomnumber (defaults to 42)可选最大缩放级别。 如果提供了tileGrid则不使用。
minZoomnumber (defaults to 0)

Optional min zoom level. Not used if tileGrid is provided.

maxResolutionnumber | undefined可选的瓷砖网格分辨率为零级。如果提供了tileGrid则不使用。
tileGridTileGrid | undefined

Tile grid.

tileLoadFunctionLoadFunction | undefined

可选的函数,加载给定URL的贴图. The default is

function(imageTile, src) {
  imageTile.getImage().src = src;
};
tilePixelRationumber (defaults to 1)贴图服务使用的像素比率。 例如,如果贴图服务宣传的是256px * 256px的贴图,但实际上发送的是512px * 512px的图像(针对retina/hidpi设备),那么tilePixelRatio就应该设置为2。 
tileSizenumber | Size (defaults to [256, 256])瓷砖服务使用的瓷砖大小。 如果提供了tileGrid则不使用。 
gutternumber (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 2 x gutter.

tileUrlFunctionUrlFunction | undefined

Optional function to get tile URL given a tile coordinate and the projection. Required if url or urls are not provided.

urlstring | undefined

URL template. Must include {x}{y} or {-y}, and {z} placeholders. A {?-?} template pattern, for example subdomain{a-f}.domain.com, may be used instead of defining each one separately in the urls option.

urlsArray.<string> | undefined

An array of URL templates.

wrapXboolean (defaults to true)

Whether to wrap the world horizontally.

transitionnumber (defaults to 250)

Duration of the opacity transition for rendering. To disable the opacity transition, pass transition: 0.

zDirectionnumber | NearestDirectionFunction (defaults to 0)

Choose whether to use tiles with a higher or lower zoom level when between integer zoom levels. See getZForResolution.

事件类型:

Fires:

方法:

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">&copy; MapTiler</a> ' +
  '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; 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:

NameTypeDescription
attributionsAttributionLike | undefined

Attributions.

attributionsCollapsibleboolean (defaults to true)

Attributions are collapsible.

cacheSizenumber | undefined

Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.

crossOriginnull | string | undefined

The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you want to access pixel data with the Canvas renderer. See Allowing cross-origin use of images and canvas - HTML: HyperText Markup Language | MDN for more detail.

interpolateboolean (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.

tileGridWMTSTileGrid

Tile grid.

projectionProjectionLike | undefined

Projection. Default is the view projection.

reprojectionErrorThresholdnumber (defaults to 0.5)

Maximum allowed reprojection error (in pixels). Higher values can increase reprojection performance, but decrease precision.

requestEncodingRequestEncoding (defaults to 'KVP')

Request encoding.

layerstring在WMTS功能中发布的层名称。 
stylestring

Style name as advertised in the WMTS capabilities.

tileClassClass<ImageTile> | undefined

Class used to instantiate image tiles. Default is ImageTile.

tilePixelRationumber (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 tilePixelRatio should be set to 2.

formatstring (defaults to 'image/jpeg')

Image format. Only used when requestEncoding is 'KVP'.

versionstring (defaults to '1.0.0')

WMTS version.

matrixSetstring

矩阵集

dimensionsObject | undefinedtile请求的额外“维度”。这是一个具有与所宣传的WMTS维类似的属性的对象。
urlstring | undefined

A URL for the service. For the RESTful request encoding, this is a URL template. For KVP encoding, it is normal URL. A {?-?} template pattern, for example subdomain{a-f}.domain.com, may be used instead of defining each one separately in the urls option.

tileLoadFunctionLoadFunction | undefined

Optional function to load a tile given a URL. The default is

function(imageTile, src) {
  imageTile.getImage().src = src;
};
urlsArray.<string> | undefined

An array of URLs. Requests will be distributed among the URLs in this array.

wrapXboolean (defaults to false)

Whether to wrap the world horizontally.

transitionnumber | undefined

Duration of the opacity transition for rendering. To disable the opacity transition, pass transition: 0.

zDirectionnumber | 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:

NameTypeDescription
preemptiveboolean (defaults to true)

If true the UTFGrid source loads the tiles based on their "visibility". This improves the speed of response, but increases traffic. Note that if set to false (lazy loading), you need to pass true as request to the forDataAtCoordinateAndResolution method otherwise no data will ever be loaded.

jsonpboolean (defaults to false)

Use JSONP with callback to load the TileJSON. Useful when the server does not support CORS..

tileJSONConfig | undefined此源的TileJSON配置。如果没有提供,则必须配置url。
urlstring | undefined提供此源配置的TileJSON url。如果没有提供,则必须配置tileJSON。 
zDirectionnumber | 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

参数:

NameTypeDescription
attributionsAttributionLike | undefined

Attributions.

crossOriginnull | string | undefined

The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you want to access pixel data with the Canvas renderer. See Allowing cross-origin use of images and canvas - HTML: HyperText Markup Language | MDN for more detail.

hidpiboolean (defaults to true)

Use the ol/Map#pixelRatio value when requesting the image from the remote server.

serverTypeServerType | undefined

The type of the remote WMS server: mapservergeoservercarmentaserver, or qgis. Only needed if hidpi is true.

imageLoadFunctionLoadFunction | undefined

Optional function to load an image given a URL.

interpolateboolean (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.

paramsObject.<string, *> | undefinedWMS请求参数(见WMS标准)。 至少需要一个LAYERS参数
projectionProjectionLike | undefined

Projection. Default is the view projection.

rationumber (defaults to 1.5)比率。1表示图像请求是地图视口的大小,2表示地图视口大小的两倍,以此类推。 
resolutionsArray.<number> | undefined

Resolutions. If specified, requests will be made for these resolutions only.

urlstring | 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:

参数:

NameTypeDescription
attributionsAttributionLike | undefined

Attributions.

crossOriginnull | string | undefined

The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you want to access pixel data with the Canvas renderer. See Allowing cross-origin use of images and canvas - HTML: HyperText Markup Language | MDN for more detail.

hidpiboolean (defaults to true)

Use the ol/Map#pixelRatio value when requesting the image from the remote server.

imageLoadFunctionLoadFunction | undefined

Optional function to load an image given a URL.

interpolateboolean (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.

paramsObject.<string, *> | undefined

ArcGIS Rest parameters. This field is optional. Service defaults will be used for any fields not specified. FORMAT is PNG32 by default. F is IMAGE by default. TRANSPARENT is true by default. BBOXSIZEBBOXSR, and IMAGESR will be set dynamically. Set LAYERS to override the default service layer visibility. See https://developers.arcgis.com/rest/services-reference/export-map.htm for further reference.

projectionProjectionLike | 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.

rationumber (defaults to 1.5)

Ratio. 1 means image requests are the size of the map viewport, 2 means twice the size of the map viewport, and so on.

resolutionsArray.<number> | undefined

Resolutions. If specified, requests will be made for these resolutions only.

urlstring | 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:

参数:

NameTypeDescription
attributionsAttributionLike | undefined

Attributions.

crossOriginnull | string | undefined

The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you want to access pixel data with the Canvas renderer. See Allowing cross-origin use of images and canvas - HTML: HyperText Markup Language | MDN for more detail.

imageExtentExtent | undefined图像在地图坐标中的范围。 这是图像的[左,下,右,上]地图坐标。 
imageLoadFunctionLoadFunction | undefined

Optional function to load an image given a URL.

interpolateboolean (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.

projectionProjectionLike | undefined

Projection. Default is the view projection.

imageSizeSize | 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.

urlstring

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:

参数

NameTypeDescription
sourcesArray.<(module:ol/source/Source~Source|module:ol/layer/Layer~Layer)>

Input sources or layers. For vector data, use an VectorImage layer.

operationOperation | undefined

Raster operation. The operation will be called with data from input sources and the output will be assigned to the raster source.

libObject | undefined

在operation中用到的一些函数

threadsnumber | undefined

By default, operations will be run in a single worker thread. To avoid using workers altogether, set threads: 0. For pixel operations, operations can be run in multiple worker threads. Note that there is additional overhead in transferring data to multiple workers, and that depending on the user's system, it may not be possible to parallelize the work.

operationTypeRasterOperationType (defaults to 'pixel')

Operation type. Supported values are 'pixel' and 'image'. By default, 'pixel' operations are assumed, and operations will be called with an array of pixels from input sources. If set to 'image', operations will be called with an array of ImageData objects from input sources.

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值