'Leaflet.js - Fit geoJSON co-ordinates on map view

I have a leaflet.js map that has points and linestrings on it that come from an external JSON file.

If I add:

map.setView(new L.LatLng(0,0), 10);

It will centre the map on the latitude and longitude 0,0. How can I set it so the map centre and zoom fit all of the points from the JSON on it?



Solution 1:[1]

Similar case with me. I drawn all the markers from GeoJson data. So I written the function, which gets called repeatedly on button click. Just try if it suits your requirements.

   function bestFitZoom()
    {
        // declaring the group variable  
        var group = new L.featureGroup;

        // map._layers gives all the layers of the map including main container
        // so looping in all those layers filtering those having feature   
        $.each(map._layers, function(ml){

           // here we can be more specific to feature for point, line etc.            
            if(map._layers[].feature) 
             {
                 group.addLayer(this)
             }
         })

         map.fitBounds(group.getBounds());
    }

The best use of writing this function is that even state of map/markers changed, it will get latest/current state of markers/layers. Whenever this method gets called all the layers will be visible to modest zoom level.

Solution 2:[2]

I needed to do this when showing a user directions from his origin to a destination. I store my list of directions in an array of L.LatLng called directionLatLngs then you can simply call

map.fitBounds(directionLatLngs);

This works because map.fitBounds takes a L.LatLngBounds object which is just an array of L.LatLng

http://leafletjs.com/reference.html#latlngbounds

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kedar.Aitawdekar
Solution 2 jeff_kile