openlayer使用 mapobx矢量切片图层时,可以通过 ol-mapbox-style 插件渲染图层 但是这插件渲染性能低 有点卡顿。
找了下 发现还是用mpaobx-gl或者maplibre-gl图层渲染集成到openlayer方式性能好。
这里以maplibre-gl为例。
import { Layer} from 'ol/layer';
import { toLonLat } from 'ol/proj'
import maplibregl from "maplibre-gl"
/**
* openlayer 集成maplibregl图层,加载maplibregl样式
* @param map 地图 openlayer map对象
* @param url maplibregl样式url ***/style.json
* @param isGlobe 是否显示地球 // isGlobe为true,则显示三维地球,否则显示墨卡托投影
* @returns {*}
*/
function loadMapboxGLStyle(map, url, isGlobe = false) {
const mbMap = new maplibregl.Map({
container: map.targetElement_.id,
center: toLonLat(map.getView().getCenter()),
attributionControl: false,
interactive: false,
style: url, // style UR
boxZoom: false,
doubleClickZoom: false,
dragPan: false,
dragRotate: false,
keyboard: false,
pitchWithRotate: false,
scrollZoom: false,
touchZoomRotate: false,
projection: isGlobe ? "globe" : "mercator", // isGlobe为true,则显示三维地球,否则显示墨卡托投影
});
const mbLayer = new Layer({
render: (frameState) => {
const canvas = mbMap.getCanvas();
const viewState = frameState.viewState;
const visible = mbLayer.getVisible();
canvas.style.display = visible ? "block" : "none";
canvas.style.position = "absolute";
const opacity = mbLayer.getOpacity();
canvas.style.opacity = opacity;
// 调整地图框中的视图参数
const rotation = viewState.rotation;
mbMap.jumpTo({
center: toLonLat(viewState.center),
zoom: viewState.zoom - 1,
bearing: (-rotation * 180) / Math.PI,
animate: false,
});
if (mbMap._frame) {
mbMap._frame.cancel();
mbMap._frame = null;
}
mbMap._render();
return canvas;
},
properties: {
mbMap
}
});
//修复加载后页面不刷新bug
const listener1= (e) =>{
if (e.type == 'sourcedata' && e.isSourceLoaded) {
// 矢量切片源已加载所有当前可见的切片
console.log('矢量切片加载完成');
// 首次加载时 需要刷新显示
mbLayer.changed()
mbMap.off('sourcedata',listener1)
}
}
mbMap.on('sourcedata',listener1);
return mbLayer;
}
使用时
import {Map,View} from "ol";
const map=new Map({
target: "map"
view: new View({
})
})
const url='***/style.json'
const vetorTileLayer=loadMapboxGLStyle(map, url,false)
map.addLayer(layer);