Search code examples
parsingleafletgeojson

Leaflet GeoJSON zoom to marker by id


I have a GeoJSON with multiple markers which are placed on the map.

Now I would like to set the view from map to one of this markers, by its 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);

How to get the marker by its id and then set the view of map, so that the marker is in centre?


Solution

  • To set the map view to a marker position (and given zoom):

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

    Now to link to markers from your GeoJSON data and refer to them via their id, you have multiple solutions available. E.g. you could save the features ID in an object mapping:

    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;
          }
        }
      }
    });
    

    Then refer to it when you want to set the map view:

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

    Demo: http://jsfiddle.net/ve2huzxw/184/

    References:

    • map.setView() Sets the view of the map (geographical center and zoom) with the given animation options.
    • map.getZoom() Returns the current zoom of the map view.
    • myMarker.getLatLng() Returns the current geographical position of the marker.