[英]Leaflet.js - Fit geoJSON co-ordinates on map view
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. 它将地图置于纬度和经度0,0的中心。 How can I set it so the map centre and zoom fit all of the points from the JSON on it?
如何设置它以使地图中心和缩放适合JSON上的所有点?
You could add all of your layers to a FeatureGroup which has a getBounds
method. 您可以将所有图层添加到具有
getBounds
方法的FeatureGroup中。 So you should be able to just say myMap.fitBounds(myFeatureGroup.getBounds());
所以你应该只能说
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方法目前至少在主分支(不是最新版本,0.3.1)中可用。
Similar case with me. 与我类似的情况。 I drawn all the markers from GeoJson data.
我从GeoJson数据中绘制了所有标记 。 So I written the function, which gets called repeatedly on button click.
所以我写了这个函数,在按钮点击时反复调用它。 Just try if it suits your requirements.
试试它是否符合您的要求。
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.
每当调用此方法时,所有图层都将对适度缩放级别可见。
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 我将方向列表存储在名为
directionLatLngs
的L.LatLng
数组中,然后您可以简单地调用
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
的数组
http://leafletjs.com/reference.html#latlngbounds http://leafletjs.com/reference.html#latlngbounds
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.