2016-12-02 48 views
0

我有我的習慣'緯度'和'經度'變量。宣傳單張。如何通過緯度和經度獲得JSON標記屬性?

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標記,並得到(用於e.x. "ID"JSON財產?

我在我的項目中使用了leaflet.js。

回答

0

您可以使用標記getLatLng()方法來訪問其latlng,然後將其與您的自定義位置相匹配。要將id綁定到圖層,最好的方法是將geoJSON特徵添加到L.GeoJSON圖層,並通過layer.feature.properties.id訪問該id或通過傳遞到L.GeoJSON選項的onEachFeature方法將該id綁定到該圖層。

然後只要你想找到匹配的通過你的GeoJSON的層使用eachlayer方法例如爲:

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}`); 
    } 
}); 
經緯度只是環層