How can I query the feature that's closest to the geocode result in Mapbox?

纵然是瞬间 提交于 2019-12-11 12:08:49

问题


I'm trying to create a Mapbox map with thousands of points. I want the user to be able to type an address and a div to be filled with information from the closest point to that address. I'm using the mapbox-gl-geocoder control

What would be perfect is if I could use something like:

geocoder.on('result', function(e) {
  var features = map.queryRenderedFeatures(e.result.center)
});

But queryRenderedFeatures doesn't accept latlong coordinates, it requires viewport coordinates.

The next thing I tried was

map.on('moveend', function () {

    var xwindow = window.innerWidth / 2;
    var ywindow = window.innerHeight / 2;
    var xywindow = {'x': xwindow, 'y': ywindow};

    var features = map.queryRenderedFeatures(xywindow);
});

That gives results that are near the queried address, but not the closest point. For instance if I geocode an address where I know a point exists, this query will return a different point a few streets away.

Is there a way to use queryRenderedFeatures to get a feature on the location that is returned by the geocode control?


回答1:


But queryRenderedFeatures doesn't accept latlong coordinates, it requires viewport coordinates.

Yes but you can use map.project that Returns a Point representing pixel coordinates, relative to the map's container, that correspond to the specified geographical location.

Once you have all the features you'll need to get the distance to each of them to find the closest. cheap-ruler would be a good choice for that.

An index like geokdbush probably doesn't make sense here as you're only running it once.



来源:https://stackoverflow.com/questions/52537727/how-can-i-query-the-feature-thats-closest-to-the-geocode-result-in-mapbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!