簡體   English   中英

在Leaflet中顯示來自geoj​​son的地圖時設置縮放

[英]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所述,您可以/也應該將地圖居中放在標記上(如果單獨使用)。 如果不是這樣,您將冒險將標記置於地圖之外,具體取決於您的縮放級別。 這是一個例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM