传单:检查对象是路径还是标记

Leaflet: check if object is Path or Marker

我有以下代码使用 Mapbox.js(当然是建立在 Leaflet.js 上)将 GeoJSON 层添加到地图中:

var orgLayer = L.geoJson(boundaries, {
    onEachFeature: onEachFeature
});
this.layerGroup.addLayer(orgLayer);

function onEachFeature(feature, layer) {
    layer.on('click', zoomToFeature, _this);
}
function zoomToFeature(e) {
    this.map.fitBounds(e.target.getBounds());
}

我遇到的问题是 GeoJSON 可能由多边形或点组成,因此 Leaflet 将图层渲染为路径或标记。当它是多边形(路径)时,这一切都很好。当它是点(标记)时,代码在 e.target.getBounds() 上失败。

这个可以理解,因为getBounds只是Leaflet中Path上的一个方法,Marker上没有。我想对于 Marker 我可以使用 e.target.getLatLng()

但是,如何修改我的代码来检查目标是标记还是路径,并使用正确的方法?

您可以编写一些涉及使用 instanceof 的代码来检查图层是否是 L.Path 或 L.Marker class.[=12 的实例=]

例如:

if (layer instanceof L.Marker) {
    //do something
} else if (layer instanceof L.Path) {
    //do something else
}