[Solved] How do I find/add Map Markers Nearest to the User (Haversine formula)

That is a good suggestion @drted, did you check out the app I linked to above? it demonstrates how to tie into a backend that does the work for you. It does search in radius and loads markers within a set radius of the user. all the phone does is send the query and load the markers!

Haversine is good. but iit only tells you distance. you’d have to do this for each point on the map, right?

function haversineDistance(coords1, coords2, isMiles) {
  function toRad(x) {
    return x * Math.PI / 180;
  }

  var lon1 = coords1[0];
  var lat1 = coords1[1];

  var lon2 = coords2[0];
  var lat2 = coords2[1];

  var R = 6371; // km

  var x1 = lat2 - lat1;
  var dLat = toRad(x1);
  var x2 = lon2 - lon1;
  var dLon = toRad(x2)
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;

  if(isMiles) d /= 1.60934;

  return d;
}
1 Like