Calculate the distance between two geopoints in Javascript
I was working on a prototype that for an geo location based app. Originally I found the algorithm that calculates the distance between two geo points on this page http://www.movable-type.co.uk/scripts/latlong.html . and then I added a little touch up to make it easier to understand and easier to use.
Enjoy! If you like this post, please Like my website by clicking the like button on the home page here.
/*
*calculate the direct distance between two geopoints.
*params:
*lat1: latitude of geopoint 1
*lon1: longitude of geopoint 1
*lat2: latitude of geopoint 2
*lon2: longitude of geopoint 2
*ouput: distance between two geopoints in km.
*example:distance_between_geopoints(43.716589,-79.340686,43.883333,-79.25);
*/
function distance_between_geopoints(lat1,lon1,lat2,lon2){
R = 6371;//earth’s radius (mean radius = 6,371km);
dLat = (lat2-lat1) * Math.PI / 180;
dLon = (lon2-lon1) * Math.PI / 180;
lat1 = lat1 * Math.PI / 180;
lat2 = lat2 * Math.PI / 180;
a = Math.sin(dLat/2) * Math.sin(dLat/2) +Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = R * c;
return d;
}



