vue项目通过openlayers加载wmts服务示例:
<template><div id="map" ref="mapContainer"></div>
</template><script>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import WMTS from 'ol/source/WMTS';
import WMTSCapabilities from 'ol/format/WMTSCapabilities';
import {get as getProjection} from 'ol/proj';
import {getTopLeft, getWidth} from 'ol/extent';
import OSM from 'ol/source/OSM';export default {name: 'WmtsMap',data() {return {map: null,wmtsCapabilitiesUrl: 'https://your-wmts-service-url?request=GetCapabilities&service=WMTS'};},mounted() {this.initMap();},methods: {async initMap() {// 创建基础地图const baseLayer = new TileLayer({source: new OSM()});// 初始化地图视图const view = new View({center: [0, 0],zoom: 2});// 创建地图实例this.map = new Map({target: this.$refs.mapContainer,layers: [baseLayer],view: view});// 加载WMTS服务await this.loadWmtsLayer();},// 重点 async loadWmtsLayer() {try {// 获取WMTS能力文档const parser = new WMTSCapabilities();const response = await fetch(this.wmtsCapabilitiesUrl);const text = await response.text();const result = parser.read(text);// 解析WMTS能力文档const options = this.getWmtsOptions(result);// 创建WMTS图层const wmtsLayer = new TileLayer({opacity: 0.7,source: new WMTS(options)});// 添加到地图this.map.addLayer(wmtsLayer);} catch (error) {console.error('加载WMTS服务失败:', error);}},getWmtsOptions(result) {// 这里我们选择第一个可用的图层和矩阵集// 实际应用中可能需要根据需求选择特定的图层和矩阵集const layer = result.Contents.Layer[0];const tileMatrixSet = result.Contents.TileMatrixSet[0];const matrixSet = result.Contents.TileMatrixSet.filter((tms) => tms.Identifier === tileMatrixSet.Identifier)[0];const projection = getProjection(matrixSet.SupportedCRS);const resolutions = [];const matrixIds = [];const {TileMatrix} = result.Contents;for (let i = 0; i < TileMatrix.length; i++) {const tileMatrix = TileMatrix[i];if (tileMatrix.TileMatrixSet === tileMatrixSet.Identifier) {matrixIds.push(tileMatrix.Identifier);resolutions.push(tileMatrix.ScaleDenominator * 0.00028 / projection.getMetersPerUnit());}}// 获取第一个资源URLconst resourceUrl = layer.ResourceURL.find((resource) => resource.resourceType === 'tile').template;return {url: resourceUrl,layer: layer.Identifier,matrixSet: matrixSet.Identifier,format: layer.Format[0],projection: projection,tileGrid: {origin: getTopLeft(projection.getExtent()),resolutions: resolutions,matrixIds: matrixIds},style: 'default',};}}
};
</script><style scoped>
#map {width: 100%;height: 100%;
}
</style>