javascript Leaflet.js - 在地图视图上拟合 geoJSON 坐标
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10246157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Leaflet.js - Fit geoJSON co-ordinates on map view
提问by James
I have a leaflet.js map that has points and linestrings on it that come from an external JSON file.
我有一个 Leaflet.js 地图,上面有来自外部 JSON 文件的点和线串。
If I add: map.setView(new L.LatLng(0,0), 10);
如果我添加: 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?
它将地图以纬度和经度 0,0 为中心。如何设置它以使地图中心和缩放适合其上 JSON 中的所有点?
回答by Jason
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());
您可以将所有图层添加到具有getBounds
方法的 FeatureGroup 。所以你应该可以说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.
L.FeatureGroup 的 getBounds 方法仅在 master 分支(不是最新版本,0.3.1)中可用,至少现在是这样。
回答by Kedar.Aitawdekar
Similar case with me. I drawn all the markersfrom GeoJsondata. So I written the function, which gets called repeatedly on button click. Just try if it suits your requirements.
跟我的情况类似。我从GeoJson数据中绘制了所有标记。所以我写了这个函数,它在按钮点击时被重复调用。试试看是否符合您的要求。
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.
编写此函数的最佳用途是即使地图/标记的状态发生变化,它也会获得标记/图层的最新/当前状态。每当调用此方法时,所有图层都将在适度缩放级别下可见。
回答by jeff_kile
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
当向用户显示从他的起点到目的地的路线时,我需要这样做。我将我的方向列表存储在一个L.LatLng
被调用的数组中,directionLatLngs
然后你可以简单地调用
map.fitBounds(directionLatLngs);
This works because map.fitBounds
takes a L.LatLngBounds
object which is just an array of L.LatLng
这是有效的,因为map.fitBounds
需要一个L.LatLngBounds
对象,它只是一个数组L.LatLng