OpenLayers地图图形显示顺序设置及组合图形绘制方法
OpenLayers 图形显示顺序与组合要素解决方案
一、调整图形显示顺序
同一个矢量图层内,OpenLayers 默认按要素添加顺序渲染(后添加的要素显示在上方),但如果想强制让圆形显示在线条上方,有两种实用方法:
方法1:给要素设置zIndex并配置图层排序规则
给圆形要素设置更高的zIndex值,再让图层按该值排序,就能控制显示层级:
function drawCircle(lon, lat) { var circleFeature = new ol.Feature({ geometry: new ol.geom.Circle( ol.proj.fromLonLat([lon, lat]), 40000 ), }); circleFeature.setStyle(style1); // 给圆形设置更高的层级值 circleFeature.set('zIndex', 10); featuresSource.addFeature(circleFeature); } function drawLine(startLon, startLat, endLon, endLat) { const lineFeature = new ol.Feature({ geometry: new ol.geom.LineString([ ol.proj.fromLonLat([startLon, startLat]), ol.proj.fromLonLat([endLon, endLat]), ]), }); lineFeature.setStyle(style); // 给线条设置更低的层级值 lineFeature.set('zIndex', 1); featuresSource.addFeature(lineFeature); } // 初始化图层时配置排序规则 const featuresLayer = new ol.layer.Vector({ source: featuresSource, // 按zIndex降序排列,数值大的要素先渲染(显示在上方) renderOrder: (a, b) => b.get('zIndex') - a.get('zIndex') });
方法2:直接在样式中设置zIndex
无需配置图层排序,直接给样式添加zIndex属性也能控制层级:
// 圆形样式(层级更高) const style1 = new ol.style.Style({ fill: new ol.style.Fill({ color: 'rgba(255,0,0,0.5)' }), stroke: new ol.style.Stroke({ color: 'red', width: 2 }), zIndex: 10 }); // 线条样式(层级更低) const style = new ol.style.Style({ stroke: new ol.style.Stroke({ color: 'blue', width: 3 }), zIndex: 1 });
二、将圆和线合并为单个组合图形
可以使用ol.geom.GeometryCollection把多个几何对象打包成一个整体,作为单个要素添加到图层,方便统一管理:
function drawCombinedShape() { // 创建两个圆形和一条线的几何对象 const circle1 = new ol.geom.Circle(ol.proj.fromLonLat([0, 0]), 40000); const circle2 = new ol.geom.Circle(ol.proj.fromLonLat([1, 1]), 40000); const line = new ol.geom.LineString([ ol.proj.fromLonLat([0, 0]), ol.proj.fromLonLat([1, 1]) ]); // 组合所有几何对象 const geometryCollection = new ol.geom.GeometryCollection([circle1, circle2, line]); // 创建单个组合要素 const combinedFeature = new ol.Feature({ geometry: geometryCollection }); // 给组合要素的不同部分设置单独样式 combinedFeature.setStyle([ new ol.style.Style({ geometry: feature => feature.getGeometry().getGeometries()[0], fill: new ol.style.Fill({ color: 'rgba(255,0,0,0.5)' }), stroke: new ol.style.Stroke({ color: 'red', width: 2 }) }), new ol.style.Style({ geometry: feature => feature.getGeometry().getGeometries()[1], fill: new ol.style.Fill({ color: 'rgba(0,255,0,0.5)' }), stroke: new ol.style.Stroke({ color: 'green', width: 2 }) }), new ol.style.Style({ geometry: feature => feature.getGeometry().getGeometries()[2], stroke: new ol.style.Stroke({ color: 'blue', width: 3 }) }) ]); featuresSource.addFeature(combinedFeature); } // 调用创建组合图形 drawCombinedShape(); map.addLayer(featuresLayer);
这样添加的要素是一个整体,选中、删除或移动时都会统一操作。
内容的提问来源于stack exchange,提问作者Saimol Simon
相关产品推荐
相关产品推荐

