在 Leaflet 中显示来自 geojson 的地图时设置缩放

Set zoom when showing map from geojson in 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());

但是当geojson文件只有一个点时,地图会放大很多。我想手动设置缩放,但不知道如何设置。

提前致谢

geojsonLayer 是一个 LayerGroup,因此您可以将其图层作为数组获取。

geojsonLayer.addData(JSON.parse(data));
if(geojsonLayer.getLayers() && geojsonLayer.getLayers().length > 1) {
   map.fitBounds(geojsonLayer.getBounds());
}
else {
   map.setZoom(defaultZoomValue);
}

编辑:正如@ghybs 所提到的,您 can/should 也将地图置于标记的中心(如果单独的话)。否则,您将冒着将标记置于地图外部的风险,具体取决于您的缩放级别。 这是一个 example.