Layer
图层大体上分为:瓦片图层、图片图层、矢量图层,它们分别对应了 source 中的、瓦片数据源、图片数据源、矢量数据源。以下从常见的一些地图服务入手,介绍底图的对接。
瓦片图层
XYZ 服务
即 xyz 数据源,是一种比较简单的底图服务:
bash
import "ol/ol.css";
import Map from "ol/Map.js";
import View from "ol/View.js";
import TileLayer from "ol/layer/Tile.js";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
const map = new Map({
target: "map",
layers: [
new TileLayer({
source: new XYZ({
url: "https://{a-d}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
attributions:
'© <a href="http://osm.org">OpenStreetMap</a> contributors, © <a href="https://carto.com/">CARTO</a>',
attributionsCollapsible: false,
}),
}),
],
view: new View({
center: fromLonLat([38.11711533115303, 55.59857050756773]),
zoom: 9,
}),
});
OSM 服务
osm 即 openstreetmap,开放的全球街道地图,是基于 XYZ 服务封装的数据源。
jsx
import "ol/ol.css";
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import Tile from "ol/layer/Tile.js";
import View from "ol/View.js";
const map = new Map({
target: "map",
layers: [
new Tile({
source: new OSM(),
}),
],
view: new View({
center: [0, 0],
zoom: 3,
}),
});
WMTS 服务
天地图发布的底图服务是 wmts 服务,下节将专门介绍天地图的对接。
图片图层
WMS 服务
使用 ImageWMS 加载 WMS 服务。注意这里使用的坐标是 web 墨卡托坐标。本示例来自Openlayers 官方示例。
jsx
import ImageWMS from "ol/source/ImageWMS.js";
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import View from "ol/View.js";
import { Image as ImageLayer, Tile as TileLayer } from "ol/layer.js";
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,
}),
});
矢量图层
矢量数据源
要给地图上添加元素,就需要添加一个基础的矢量数据源,
jsx
import "ol/ol.css";
import Map from "ol/Map.js";
import View from "ol/View.js";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
// 矢量图层
const vectorLayer = new VectorLayer({
source: new VectorSource(),
});
const map = new Map({
target: "map",
layers: [vectorLayer],
view: new View({
center: fromLonLat([109.06450587297525, 34.18640389101999]),
zoom: 8,
}),
});
MVT 服务
MVT(MapBox Vector Tile)是一种地图矢量切片格式,由 Mapbox 公司开发和推出。 它使用了矢量数据的切片化和压缩技术,将地理数据切割成小块的矢量切片,以便在 Web 地图和移动应用程序中进行快速加载和渲染。本示例来自Openlayers 官方示例。
jsx
import MVT from "ol/format/MVT.js";
import Map from "ol/Map.js";
import VectorTileLayer from "ol/layer/VectorTile.js";
import VectorTileSource from "ol/source/VectorTile.js";
import View from "ol/View.js";
const map = new Map({
target: "map",
view: new View({
center: [0, 0],
zoom: 2,
}),
layers: [
new VectorTileLayer({
source: new VectorTileSource({
format: new MVT(),
url: "https://basemaps.arcgis.com/arcgis/rest/services/World_Basemap_v2/VectorTileServer/tile/{z}/{y}/{x}.pbf",
}),
}),
],
});