Skip to content

Instantly share code, notes, and snippets.

@nicordev
Created December 24, 2018 17:04
Show Gist options
  • Save nicordev/ef62ece58596d41d2b88896cf995da4e to your computer and use it in GitHub Desktop.
Save nicordev/ef62ece58596d41d2b88896cf995da4e to your computer and use it in GitHub Desktop.
Calculate the distance between 2 points knowing their longitude and latitude
/**
* Retourne la distance entre 2 points avec des coordonnées géographiques en mètres ou kilomètres
* @param lat1 la latitude du point 1
* @param lng1 la longitude du point 1
* @param lat2 la latitude du point 2
* @param lng2 la longitude du point 2
* @param [unit] 'k' pour un résultat en kilomètre
* @return la distance en mètres ou kilomètres
*/
function calculateDistanceLatLng(lat1, lng1, lat2, lng2, unit = 'm') {
earth_radius = 6378137; // Terre = sphère de 6378km de rayon
rlo1 = deg2rad(lng1);
rla1 = deg2rad(lat1);
rlo2 = deg2rad(lng2);
rla2 = deg2rad(lat2);
dlo = (rlo2 - rlo1) / 2;
dla = (rla2 - rla1) / 2;
a = (Math.sin(dla) * Math.sin(dla)) + Math.cos(rla1) * Math.cos(rla2) * (Math.sin(dlo) * Math.sin(dlo));
d = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
meter = (earth_radius * d);
if (unit == 'k') {
return meter / 1000;
}
return meter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment