Red*_*ion 1 javascript zooming geojson leaflet
我正在使用Leaflet.js在地图中显示geojson文件,我有以下代码:
// 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());
Run Code Online (Sandbox Code Playgroud)
但是当geojson文件只有一个点时,地图会缩放很多.我想手动设置缩放,但我无法弄清楚如何.
提前致谢
geojsonLayer是一个LayerGroup,因此您可以将其图层作为数组.
geojsonLayer.addData(JSON.parse(data));
if(geojsonLayer.getLayers() && geojsonLayer.getLayers().length > 1) {
map.fitBounds(geojsonLayer.getBounds());
}
else {
map.setZoom(defaultZoomValue);
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如@ghybs所提到的,你可以/也应该将地图放在标记上(如果单独的话).如果没有,您可以冒险将标记放在地图之外,具体取决于您的缩放级别.这是一个例子.