【问题标题】:How to auto zoom to a polygon in leaflet?如何自动缩放到传单中的多边形?
【发布时间】:2017-03-16 16:13:03
【问题描述】:

我的 geoJson 格式是这样的:

statesData.features.push({  
   "type":"Feature",
   "id":"AFG",
   "properties":{  
      "name":"Afghanistan"
   },
   "geometry":{  
      "type":"Polygon",
      "coordinates":[  
         [  
            [  
               61.210817,
               35.650072
            ],
            [  
               62.230651,
               35.270664
            ],
            [  
               62.984662,
               35.404041
            ],

我正在尝试读取这些坐标并将它们设置为

        var coord = statesData.features[0].geometry.coordinates;
        lalo = L.GeoJSON.coordsToLatLng(coord);
        map.setView(lalo, 18);

The documentation says:

coordsToLatLng( coords ) 将用于的函数 将 GeoJSON 坐标转换为 LatLng 点(如果未指定, 坐标将被假定为 WGS84 — 标准 [经度,纬度] 度数)。

但我在控制台中收到此错误

未捕获的错误:无效的 LatLng 对象:(未定义, 61.210817,35.650072,62.230651,35.270664,62.984662,35.404041...

更新

第一个答案是正确的,因为它解决了上述问题,但是,它将地图缩放到第一组坐标,而我真正想要实现的是能够加载页面,地图自动缩放到多边形(我只加载一个多边形)。

This example is the closest i could find

【问题讨论】:

  • 坐标是坐标数组,数组里面,数组里面。至少一个数组不是太多了吗? setView()可以处理多个坐标吗?
  • @JJJ 我正在尝试自动缩放到多边形
  • 还有一个coordsToLatLngs() 函数(注意复数“s”)可以处理coordinates 数组([[[],[],...],[[],[],...]])。 coordsToLatLng() 只会转换一个坐标。您必须在coordinates 中选择一个纬度/经度对。 setView() 也只会使用一个坐标(纬度/经度)。

标签: javascript jquery json leaflet


【解决方案1】:

感谢我got from here 的回答,解决方案是使用leaflet layerGroup

Following leaflet example 因为这就是我正在使用的,根据他们的代码和我得到的其他答案,这对我有用。根据我的项目,我使用 php 位来获取我需要的国家/地区名称。以下获取一个名称,如果在 geoJson 中有类似的名称,则比较它,如果有,则将地图居中并缩放到该多边形:

geojson = L.geoJson(statesData, {
  style: style,
  onEachFeature: onEachFeature
}).addTo(map);

<?php 
    $myCountry = usp_get_meta(false, 'usp-custom-3');
    $fixedname = ucfirst($myCountry); 
?>

geojson.eachLayer(function (layer) {
  if (layer.feature.properties.name === "<?php echo $fixedname; ?>") {
    // Zoom to that layer.
    map.fitBounds(layer.getBounds());
  }
});

【讨论】:

    【解决方案2】:

    您正在传递一个数组数组作为参数。 coordsToLatLng 没想到会这样。它只需要一个数组,即坐标:https://www.dartdocs.org/documentation/leaflet/0.0.1-beta.1/leaflet.layer/GeoJSON/coordsToLatLng.html

    所以你的代码实际上必须是:

    var coord = statesData.features[0].geometry.coordinates[0][0];
    lalo = L.GeoJSON.coordsToLatLng(coord);
    map.setView(lalo, 18);
    

    这将获得双数组中第一个点的坐标。顺便说一句,我很确定双数组不是你真正想要的。

    【讨论】:

    • 我实际上并没有,我只是将一个多边形动态添加到一个国家,当我加载页面时我试图放大该多边形,我尝试了 fitBounds 并阅读所有地方和我无法理解,直到我走到这一步,但没有工作:(
    • @rob.m 是的,但是,该数组从何而来?那是一个 3 维数组,这里有点出乎意料。如果您手动创建该数组,那么您肯定做错了。你在做coordinates: [ [ [x,y],[x,y],[x,y] ] ],当它肯定是coordinates: [ [x,y],[x,y],[x,y] ]
    • 这是geoJson而不是json
    • 这是多边形的格式,在 (RFC7946) 中定义:geojson.org/wikipedia
    • @rob.m 是的,让我们看看有没有经验更丰富的用户在这里带来一点亮点。
    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 2015-10-29
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    相关资源
    最近更新 更多