kavallo

Function to calculate distance between two coordinates

Apr 7th, 2017
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  2.   var R = 6371; // Radius of the earth in km
  3.   var dLat = deg2rad(lat2-lat1);  // deg2rad below
  4.   var dLon = deg2rad(lon2-lon1);
  5.   var a =
  6.     Math.sin(dLat/2) * Math.sin(dLat/2) +
  7.     Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
  8.     Math.sin(dLon/2) * Math.sin(dLon/2)
  9.     ;
  10.   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  11.   var d = R * c; // Distance in km
  12.   return d;
  13. }
  14.  
  15. function deg2rad(deg) {
  16.   return deg * (Math.PI/180)
  17. }
Add Comment
Please, Sign In to add comment