首页 > 解决方案 > Leaflet KNN 查找最近的标记

问题描述

我正在尝试使用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)
}

标签: leaflet

解决方案


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

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();

});

在此处查看一个工作示例


推荐阅读