10

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.

3 Answers 3

8

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)

2
6

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)

2
  • Hey, pretty cool I'am going to check it out! if works all give you the points :) Commented Jul 25, 2014 at 16:58
  • One problem I have found is it only gives you a single point, which looks like the exact center. It lets you use a radius, but we have markers which can change size. I'm going to use the iconSize, but this still seems like something which could be done by the plugin.
    – trysis
    Commented Mar 21, 2017 at 15:13
2

You could use the turf.js library

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.