OpenLayers矢量图层按GeoJson的station属性设置不同图标问题求助
问题根因
代码逻辑存在顺序错误:预先遍历所有要素修改onLoadSrc变量,最终仅生成1个全局样式对象绑定给整个矢量图层,所有要素共享同一个样式,因此只会使用循环结束后onLoadSrc的最终值。
解决方案
OpenLayers 矢量图层的style参数支持传入回调函数,单个要素渲染时会自动调用该函数并传入当前要素作为参数,可在回调内根据要素属性动态返回对应样式。
修改后代码如下:
let startDatajson = (new ol.format.GeoJSON({ dataProjection : 'EPSG:4326', featureProjection: 'EPSG:3857', })).readFeatures(startJson); let stationStartSource = new ol.source.Vector({ features: startDatajson }); startStationsLayer = new ol.layer.Vector({ source: stationStartSource, visible:true, title:"ultimasEstaciones", // 动态样式回调,每个要素渲染时自动执行 style: function(feature) { const getStation = feature.get("Station"); const onLoadSrc = getStation === "NNAA" ? "assets/img/alert-smaller.png" : "assets/img/blue-triangle.png"; return new ol.style.Style({ image: new ol.style.Icon({ anchor: [0.5,0.5], size: [28,19], offset: [1,1], scale: 1, src: onLoadSrc }) }) } }); map.addLayer(startStationsLayer);
可选性能优化
如果站点类型较多,可提前预创建所有图标实例,避免每次渲染重复创建样式对象:
// 预缓存所有图标实例 const iconMap = { "NNAA": new ol.style.Icon({ anchor: [0.5,0.5], size: [28,19], offset: [1,1], scale: 1, src: "assets/img/alert-smaller.png" }), "default": new ol.style.Icon({ anchor: [0.5,0.5], size: [28,19], offset: [1,1], scale: 1, src: "assets/img/blue-triangle.png" }) } // 样式回调直接复用已创建的图标实例 style: function(feature) { const station = feature.get("Station"); return new ol.style.Style({ image: iconMap[station] || iconMap.default }) }
内容的提问来源于stack exchange,提问作者Ander Canales Medina
相关产品推荐
相关产品推荐

