Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 842
James Avatar asked Apr 20 '12 12:04

James


People also ask

How do you add GeoJSON to a leaflet map?

GeoJSON objects are added to the map through a GeoJSON layer. To create it and add it to a map, we can use the following code: L. geoJSON(geojsonFeature).

What is Tilelayer in leaflet?

Used to load and display tile layers on the map, implements ILayer interface.

How do I view GeoJSON?

If you have a geojson file on your local hard drive or network and want to view/use it in QGIS, you can just drag and drop it from the Browser Panel into the Layers Panel or just double click on the file will add it to the Layers Panel. If trying to add the original *.


3 Answers

You could add all of your layers to a FeatureGroup which has a getBounds method. So you should be able to just say myMap.fitBounds(myFeatureGroup.getBounds());

The getBounds method for L.FeatureGroup is only available in the master branch (not the latest version, 0.3.1), for now at least.

like image 184
Jason Avatar answered Oct 11 '22 02:10

Jason


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.

like image 30
Kedar.Aitawdekar Avatar answered Oct 11 '22 02:10

Kedar.Aitawdekar


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

like image 1
jeff_kile Avatar answered Oct 11 '22 02:10

jeff_kile