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?
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).
Used to load and display tile layers on the map, implements ILayer interface.
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 *.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With