Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find closest marker leaflet.js

I was wondering if there is actually some way to find markers near my position using leaflet.js. The first think to come to my head is to store lat and lng of my position and then iterate over an array of lat and lng markers placing them in an array an then sort that array. I am not sure if this is a good option because if you have a million markers in the map is going to take a while.

Pseudo code

var myLatLng = [34,56];
var markers = [[20,30],[10,20],[12,-100],[54,90],[-10, -20],[20,20]];
var closests = [];
function findNearestMarker (myPosition, nearestMarkers){
 for(var i = 0; i < nearestMarkers.length){
     if((nearestMarkers[i][0] - myPosition[0]) < 100 && (nearestMarkers[i][1] - myPosition[1]) < 100 ){
         closests.push(nearestMarkers[i])
     }
 }
}

I am actually starting with maps and dont know so many approaches, I will also like to use open street maps for this project, but, if someone know and aproach using google maps or another services it will be welcomed.

like image 922
Jhonnatan Gonzalez Rodriguez Avatar asked Mar 24 '14 23:03

Jhonnatan Gonzalez Rodriguez


3 Answers

Leaflet.GeometryUtil is the best solution I found for that (https://github.com/makinacorpus/Leaflet.GeometryUtil). Use L.GeometryUtil.closestLayer.

It's more practical to use than leaflet-knn because you can send an array of layers (markers for examples), instead of only a geojson layer. But more importantly, it seems faster (about 90% faster with a set of 500+ markers, cold start, on Chrome 36, although on FF31 it's comparable)

like image 84
Erik Avatar answered Oct 16 '22 08:10

Erik


Try leaflet-knn, which does nearest-neighbor lookups: given a point and a bunch of other points, it finds the nearest neighbors (as it says on the tin)

like image 37
tmcw Avatar answered Oct 16 '22 08:10

tmcw


You could use the turf.js library

http://turfjs.org/examples/turf-nearest/

like image 24
Keith Avatar answered Oct 16 '22 07:10

Keith