3

I want it to auto zoom / zoom to center when any GeoJSON file is loaded on a Leaflet map. Help please.

$.getJSON("{{asset("storage/upload/shapefiles/districts/atd_district_level.geojson")}}",function(data){
                // add GeoJSON layer to the map once the file is loaded
                L.geoJson(data, {

                    style: {color: "#999", weight: 2, fillColor: "#00ad79", fillOpacity: .6},

                    onEachFeature: function (feature, layer) {
                        layer.bindPopup("<strong>" + feature.properties['DISTRICT'])
                    }

                }).addTo(map);
            });

I am new with Leaflet maps.

1
  • There's no such thing as a GeoJSON shapefile, they are both data formats.
    – nmtoken
    Commented Jul 19, 2017 at 19:16

2 Answers 2

5

If you keep a reference to the geojson layer you can get its bounds, and then fit the map to it.

$.getJSON("{{asset("storage/upload/shapefiles/districts/atd_district_level.geojson")}}",function(data){
                // add GeoJSON layer to the map once the file is loaded
                jsonLayer = L.geoJson(data, {

                    style: {color: "#999", weight: 2, fillColor: "#00ad79", fillOpacity: .6},

                    onEachFeature: function (feature, layer) {
                        layer.bindPopup("<strong>" + feature.properties['DISTRICT'])
                    }

                })
               jsonLayer.addTo(map);
               map.fitBounds(jsonLayer.getBounds());
            });
0
0

Give a varible name to L.geoJson tag. call it via fitBounds

var cable=L.geoJson(cable, {
    style: Cablestyle,
    onEachFeature: onEachFeatureCable
   }).addTo(map);

map.fitBounds(cable.getBounds());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.