如何向VectorTileLayer的style回调函数传入keyGridsAsGeoJSON参数
问题原因
你遇到的是典型的局部变量屏蔽外层变量的问题:
- OpenLayers 的
VectorTileLayer的style配置项对应的回调函数,第一个参数默认是当前待渲染的矢量瓦片要素,类型就是你打印出来的RenderFeature - 你外层声明了变量
var k = keyGridsAsGeoJSON,但又给style回调的形参命名为k,作用域优先级更高的局部参数k直接覆盖了外层的k变量,所以你在回调内拿到的永远是OpenLayers传入的要素对象,不是你预期的GeoJSON数据。
解决方法
把style回调的形参改成其他名字,比如feature即可,修改后的代码示例如下:
public visualisePolygonsAsMVTTilesOnMapWithColors(map,keyGridsAsGeoJSON,fillColor,strokeColor,text){ var features = []; var iter = 0 var k = keyGridsAsGeoJSON console.log("keyGridsAsGeoJSON:",keyGridsAsGeoJSON) keyGridsAsGeoJSON.forEach(function(keyGridAsGeoJSON) { let polygonGeometry = [keyGridAsGeoJSON['features'][0]['geometry']] polygonGeometry.forEach(function(geojson) { var geometry = new GeoJSON().readGeometry(geojson, { dataProjection: 'EPSG:4326', featureProjection: map.getView().getProjection() }); features.push(new Feature(geometry)); }); }); var vectorTile = new VectorTileLayer({ source: new VectorTileSource({ format: new MVT(), url: environment.LocalHostForTileLayerSourceAsMVTTileForZXYWS + "/{z}/{x}/{y}" }), // 把形参名从k改成feature,避免变量覆盖 style: function (feature){ console.log("features:",features) // 此时打印的k就是外层你存的keyGridsAsGeoJSON内容了 console.log("k:",k) // 后续你可以结合feature和k的内容自定义渲染样式 } }); return vectorTile; }
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

