传单.js - 在地图视图上拟合地理 JSON 坐标

Leaflet.js - Fit geoJSON co-ordinates on map view

本文关键字:拟合 JSON 坐标 视图 js 地图 传单      更新时间:2023-09-26

我有一个传单.js地图,上面有来自外部JSON文件的点和线串。

如果我添加:

map.setView(new L.LatLng(0,0), 10);

它将使地图在纬度和经度 0,0 上居中。如何设置它,使地图中心和缩放适合其上 JSON 中的所有点?

您可以将所有图层添加到具有getBounds方法的特征组中。所以你应该可以说myMap.fitBounds(myFeatureGroup.getBounds());

L.FeatureGroup 的 getBounds 方法仅在主分支(不是最新版本 0.3.1)中可用,至少目前如此。

与我的情况类似。我从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());
    }

编写此函数的最佳用途是,即使地图/标记的状态发生变化,它也会获得标记/图层的最新/当前状态。每当调用此方法时,所有图层都将以适度的缩放级别可见。

在向用户显示从起点到目的地的方向时,我需要这样做。 我将方向列表存储在一个名为directionLatLngsL.LatLng数组中,然后您可以简单地调用

map.fitBounds(directionLatLngs);

这是有效的map.fitBounds因为它需要一个L.LatLngBounds对象,该对象只是一个L.LatLng数组

http://leafletjs.com/reference.html#latlngbounds