Leaflet GeoJSON 按 id 缩放到标记

Leaflet GeoJSON zoom to marker by id

我有一个带有多个标记的 GeoJSON,这些标记放置在地图上。

现在我想通过其 id 将地图中的视图设置为该标记之一。

var map = L.map('map');

var osm = L.tileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
    maxZoom: 19,
    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>, Tiles courtesy of <a href="http://hot.openstreetmap.org/" target="_blank">Humanitarian OpenStreetMap Team</a>'
});

var geojsonFeature = [{
    "type": "Feature",
    "properties": {
        "id": "marker1",
        "name": "Coors Field"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.99404, 39.75621]
    }
}, {
    "type": "Feature",
    "properties": {
        "id": "marker2",
        "name": "School",
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-104.69404, 38.85621]
    }
}];

var markerLayer = L.geoJson(null, {
    pointToLayer: function(feature, latlng) {
        return L.marker(latlng, {});

    },
    onEachFeature: function(feature, layerinfo) {
        if (feature.properties) {
            var content = "<table class='table table-striped table-bordered table-condensed'>" + "<tr><th>Name</th><td>" + feature.properties.name + "<table>";

            layerinfo.bindPopup(content, {
                closeButton: true
            });
        }
    }
});

markerLayer.addData(geojsonFeature);
markerLayer.addTo(map);
map.fitBounds(markerLayer.getBounds());
map.setZoom(16);
map.addLayer(osm);

如何通过id获取marker,然后设置地图视图,使marker居中?

将地图视图设置为标记位置(并给定缩放):

map.setView(myMarker.getLatLng(), myZoom);

现在 link 从您的 GeoJSON 数据中提取标记并通过它们的 ID 引用它们,您有多种解决方案可用。例如。您可以将功能 ID 保存在对象映射中:

var markersById = {};

var markerLayer = L.geoJson(null, {
  pointToLayer: function(feature, latlng) {
    return L.marker(latlng, {});

  },
  onEachFeature: function(feature, layerinfo) {
    if (feature.properties) {
      var content = "<table class='table table-striped table-bordered table-condensed'>" + "<tr><th>Name</th><td>" + feature.properties.name + "<table>";

      layerinfo.bindPopup(content, {
        closeButton: true
      });

      // Save the layer into markersById if it has an id.
      if (feature.properties.id) {
        markersById[feature.properties.id] = layerinfo;
      }
    }
  }
});

然后在设置地图视图时参考:

map.setView(markersById[id].getLatLng(), map.getZoom());

演示:http://jsfiddle.net/ve2huzxw/184/

参考文献: