Leaflet Zoom – Zoom to Polygon Bounds on Click Using GeoJSON

geojsonleafletmarkersPHPzoom

I have a leaflet map with a lot of polygons (borders). I would like to zoom to the bounds on the polygon, when the user click.

Until now its only possible for me to zoom to the the bounds of all the polygons in the GeoJSON file.

var map = L.map('map')
    .addLayer(mapboxTiles)
    .setView([50.444508, -80.499491], 10);

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

markers.on('click', function() {
    map.fitBounds(markers.getBounds());
});

markers.addTo(map);

$.getJSON('contry.php', function (data) {
     markers.addData(data)
});

what to change here?

markers.on('click', function() {
    map.fitBounds(markers.getBounds());
});

Best Answer

Probably:

markers.on("click", function (event) {
    // Assuming the clicked feature is a shape, not a point marker.
    map.fitBounds(event.layer.getBounds());
});

You may want to detect if the clicked feature is a marker (point feature), and act accordingly, as it will not have the getBounds() method.

References:

Note: in the case of attaching a listener onto a Feature Group (like your GeoJSON group layer), event.target gives the entire group, not the specific single feature.