【问题标题】:Leaflet. How I can get JSON marker property by Latitude and Longitude?传单。如何通过纬度和经度获取 JSON 标记属性?
【发布时间】:2016-12-02 09:20:06
【问题描述】:

我有我的自定义“纬度”和“经度”变量。

var custom_loc = [50.34434, 63.23442]

我还有JSON 数据,其中的点为GeoJSON 格式。

 {
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [50.34434, 63.23442]
  },
  "properties": {
    "id" : "1",
    "name": "Good place"
  }
}

如何通过"custom_loc" 找到JSON 标记并获得JSON 属性(例如"ID")?

我在我的项目中使用 Leaflet.js。

【问题讨论】:

    标签: json ajax leaflet openstreetmap geojson


    【解决方案1】:

    您可以使用标记getLatLng() 方法访问其纬度,然后将其与您的自定义位置匹配。要将 id 绑定到层,最好的办法是将 geoJSON 功能添加到 L.GeoJSON 层并通过 layer.feature.properties.id 访问 id 或通过传递给 L.GeoJSON 选项的 onEachFeature 方法将 id 绑定到层。

    然后,每当您想找到具有匹配 latlng 的图层时,只需使用 eachlayer 方法遍历您的 geojson 图层,例如:

    var custom_loc = [50.34434, 63.23442];
    var geoJSON = L.geoJson(
          {
          "type": "FeatureCollection",
          "features": [
            {
              "type": "Feature",
              "geometry": {
                "type": "Point",
                "coordinates": [50.34434, 63.23442]
              },
              "properties": {
                "id" : "1",
                "name": "Good place"
              }
            }
          ]
        },
        {
          onEachFeature: function(feature, layer) {
            layer.options.id = feature.properties.id;
          }
        }
    );
    map.addLayer(geoJSON);
    
    geoJSON.eachLayer(l => {
      var coords = l.feature.geometry.coordinates;
      var latlng = l.getLatLng();
      if (latlng.lat === custom_loc[1] && latlng.lng === custom_loc[0]) {
        console.log(`Latlng match: ${l.options.id}`)
      }
      if (coords[0] === custom_loc[0] && coords[1] === custom_loc[1]) {
        console.log(`Latlng match: ${l.options.id}`);
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 1970-01-01
      • 2016-10-30
      • 2011-01-05
      • 2012-06-08
      • 2016-04-07
      • 2013-03-23
      • 1970-01-01
      • 2012-07-30
      相关资源
      最近更新 更多