单张KNN查找最近的标记

时间:2019-06-12 12:14:39

标签: leaflet

我正在尝试使用Leaflet-knn

在特定位置的地图上找到最近的标记

let nearest = leafletKnn(leafletGeoJson).nearest(L.latLng(38, -78), 5)

leafletGeoJson包含我之前在地图上设置的标记的所有位置。

nearest返回具有_leaflet_id的对象数组,我想通过它们选择地图上的标记:

map._layers[nearest[0]],但是它不起作用。由于某种原因,它不返回标记的_leaflet_id,而是返回新的传单对象。

我用错了吗?

编辑:

var geoJson = []
for (let i in s) {
  let s = s[i],
  ll = L.latLng(s.Location[0], s.Location[1]),
  llArr = { "type": "Point", "coordinates": [s.Location[0], s.Location[1]] },

  geoJson.push(llArr)

  L.marker(ll, { icon: icon }).on('click', function (e) {
    // some stuffg
  }).addTo(map)
}

1 个答案:

答案 0 :(得分:0)

leaflet-knn索引的.nearestLayer().nearest()方法都返回一个数据结构,该数据结构包含对L.Layer的引用,该引用包含最近的点(即L.MarkerL.Polyline,取决于您的geojson数据中包含的内容),例如:

var geojsonlayer = L.geoJson(geojsondata).addTo(map);

searchIndex = leafletKnn(geojsonlayer);

map.on('click', function(ev){
  // Perform a KNN search with maximum 1 element in the result set, 
  // then pick the first result from the result set.
  var nearestResult = searchIndex.nearest(ev.latlng, 1)[0];

  // The result has 'lat' and 'lon' properties...
  console.log('nearest lat: ', nearestResult.lat);
  console.log('nearest lng: ', nearestResult.lon);

  // ... as well as a 'layer' property containing the reference to the `L.Layer`,
  // which we can do something with.
  nearestResult.layer.bindPopup("I'm nearest to where you clicked!").openPopup();

});

查看working example here