Leaflet矢量图层弹窗中获取目标要素FeatureId的方法
解决Leaflet VectorGrid弹窗中获取FeatureId的问题
嘿,我来帮你搞定这个问题!你已经在getFeatureId里正确返回了有效的要素ID,但要在弹窗里拿到它,其实可以通过两种简单直接的方式实现:
方法一:动态绑定弹窗内容
直接在bindPopup时传入一个函数,这个函数会在每次点击要素时被调用,并且能拿到对应的要素图层对象,从中提取你需要的FeatureId:
var map = L.map('map').setView([53.505, -7.09], 7); L.tileLayer('https://{s}.etc.etc/{z}/{x}/{y}.png', { attribution: 'osm..' }).addTo(map); var VectorTileOptions = { rendererFactory: L.canvas.tile, attribution: '', interactive: true, getFeatureId:function(feat){ return feat.properties.routes } }; var TilesPbfLayer = L.vectorGrid.protobuf(tileurl, VectorTileOptions).addTo(map); // 直接用函数生成弹窗内容 TilesPbfLayer.bindPopup(function(layer) { // layer.feature.id 就是你在getFeatureId中返回的ID值 return "Feature ID: " + layer.feature.id; });
这样每次点击矢量瓦片里的要素,弹窗就会自动显示对应的FeatureId了。
方法二:监听点击事件手动控制弹窗
如果你想保留独立的popup变量,也可以监听图层的click事件,在回调中获取FeatureId并设置弹窗内容:
var map = L.map('map').setView([53.505, -7.09], 7); L.tileLayer('https://{s}.etc.etc/{z}/{x}/{y}.png', { attribution: 'osm..' }).addTo(map); var VectorTileOptions = { rendererFactory: L.canvas.tile, attribution: '', interactive: true, getFeatureId:function(feat){ return feat.properties.routes } }; var TilesPbfLayer = L.vectorGrid.protobuf(tileurl, VectorTileOptions).addTo(map); var popup = L.popup(); TilesPbfLayer.on('click', function(e) { // 从点击事件中拿到要素图层,提取ID var featureId = e.layer.feature.id; popup.setContent("Feature ID: " + featureId) .setLatLng(e.latlng) .openOn(map); });
小提示
你之前用的popupopen事件之所以拿不到FeatureId,是因为这个事件的回调参数里没有直接关联被点击的要素信息,而点击事件或者bindPopup的函数参数能直接获取到对应的要素图层,这才是正确的获取路径哦。
内容的提问来源于stack exchange,提问作者Mark Lester




