Reputation: 1006
I'm using Leaflet.js to show geojson files in a map and I have the following code:
// Set the map and the geojson as pointed in the tutorials
var geojsonLayer = new L.GeoJSON(null, {
onEachFeature: function (feature, layer) {
if (feature.properties) {
var popupString = '<div class="popup">';
for (var k in feature.properties) {
var v = feature.properties[k];
popupString += k + ': ' + v + '<br />';
}
popupString += '</div>';
layer.bindPopup(popupString, {
maxHeight: 200
});
}
}
});
map.addLayer(geojsonLayer);
L.control.layers({'Road': road_layer, 'Satellite': satellite_layer}, {'GeoJSON': geojsonLayer}).addTo(map);
//...
// Load file and get its content in the data var
//...
geojsonLayer.addData(JSON.parse(data));
map.fitBounds(geojsonLayer.getBounds());
But when the geojson file has only a point, the map zooms to much. I would like to set the zoom manually but I can't figure out how.
Thanks in advance
Upvotes: 1
Views: 3069
Reputation: 10008
geojsonLayer is a LayerGroup so you can get its layers as an array.
geojsonLayer.addData(JSON.parse(data));
if(geojsonLayer.getLayers() && geojsonLayer.getLayers().length > 1) {
map.fitBounds(geojsonLayer.getBounds());
}
else {
map.setZoom(defaultZoomValue);
}
EDIT: As mentioned by @ghybs, you can/should also center the map on the marker (if alone). If not, you take the risk to have the marker outside the map depending on your zoom level. Here is an example.
Upvotes: 8