我正在尝试定义一堆像这样的Leaflet多边形:
var poly = new L.Polygon([
[10.1840229, 36.8906981],
[10.1840393, 36.8906669],
[10.1840989, 36.8906868],
[10.1840826, 36.890718],
[10.1840229, 36.8906981]
], {
'id': 'someId'
});
然后我将这些多边形分组到GroupLayer中,如下所示:
var group = new L.LayerGroup([poly1, poly2, ..., polyn]);
group.addTo(map);
我可以使用group.getLayer()通过Id找到这些多边形吗?或者我是否需要以不同方式定义图层/多边形才能执行此操作?
Leaflet为每个层分配自己的唯一ID:
var marker = new L.Marker(...); console.log(marker._leaflet_id) // 24 var polygon = new L.Polygon(...); console.log(polygon._leaflet_id) // 25
所述getLayer
的方法L.LayerGroup
,L.FeatureGroup
以及L.GeoJSON
把这些ID作为一个参数:
var layerGroup = L.LayerGroup([marker, polygon]); layerGroup.getLayer(24); // returns the marker layerGroup.getLayer(25); // returns the polygon
您也可以轻松分配自己的ID:
var marker = new L.Marker(...); marker.id = 'foo'; var polygon = new L.Polygon(...); polygon.id = 'bar';
然后像这样获取它们:
var layerGroup = L.LayerGroup([marker, polygon]); layerGroup.eachLayer(function (layer) { if (layer.id === 'foo') // it's the marker if (layer.id === 'bar') // it's the polygon });
您可以轻松地将其放入函数中并将其包含在L.LayerGroup
:
L.LayerGroup.include({ customGetLayer: function (id) { for (var i in this._layers) { if (this._layers[i].id == id) { return this._layers[i]; } } } }); var layerGroup = L.LayerGroup([marker, polygon]); layerGroup.customGetLayer('foo'); // returns the marker layerGroup.customGetLayer('bar'); // returns the polygon
编辑:没有在您的示例中发现ID,直到缩进编辑.您也可以像在示例中一样将其指定为选项,并创建自定义get函数来检索图层:
L.LayerGroup.include({ customGetLayer: function (id) { for (var i in this._layers) { if (this._layers[i].options.id == id) { return this._layers[i]; } } } }); var layerGroup = L.LayerGroup([marker, polygon]); layerGroup.customGetLayer('foo'); // returns the marker layerGroup.customGetLayer('bar'); // returns the polygon
如果您需要识别图层的类型,可以使用instanceof来执行此操作:
instanceof运算符测试对象在其原型链中是否具有构造函数的prototype属性.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof
var layerGroup = L.LayerGroup([marker, polygon]); layerGroup.eachLayer(function (layer) { if (layer instanceof L.Marker) // it's the marker if (layer instanceof L.Polygon) // it's the polygon });
但请记住,当您发现自己做出共同选择时,理想情况下应将这些功能放在单独的图层/功能组中.