3

I have a list with 50 items:

var mylocations = [{'id':'A', 'loc':[-21,2]},...,];

How can I in leaflet or JavaScript most efficiently make it such that if I accept an input of a specific location [<longitude>,<latitude>], a radius (e.g. 50 miles)... I can get all of the "mylocations" that fall within that circle?

Using external libraries is fine.

Marty
  • 39,033
  • 19
  • 93
  • 162
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 1
    http://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula – Marty Nov 08 '15 at 23:58

1 Answers1

10

Leaflet's L.LatLng objects include a distanceTo method:

Returns the distance (in meters) to the given LatLng calculated using the Haversine formula.

http://leafletjs.com/reference.html#latlng-distanceto

var inRange = [], latlng_a = new L.LatLng(0, 0), latlng_b;

locations.forEach(function (location) {
    latlng_b_ = new L.LatLng(location.pos[0], location.pos[1]);
    if (latlng_a.distanceTo(latlng_b) < 80.4672) {
        inRange.push(location);
    }
});
iH8
  • 27,722
  • 4
  • 67
  • 76