latitude longitude to km javascript 1

latitude longitude to km javascript

function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(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; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

Here is what the above code is Doing:
1. We’re defining a function called getDistanceFromLatLonInKm that takes in 4 parameters: lat1, lon1, lat2, lon2.
2. We’re defining a variable called R that is equal to 6371. This is the radius of the earth in km.
3. We’re defining a variable called dLat that is equal to the difference between lat2 and lat1.
4. We’re defining a variable called dLon that is equal to the difference between lon2 and lon1.
5. We’re defining a variable called a that is equal to the sine of dLat divided by 2 times the sine of dLat divided by 2 plus the cosine of lat1 times the cosine of lat2 times the sine of dLon divided by 2 times the sine of dLon divided by 2.
6. We’re defining a variable called c that is equal to 2 times the arctangent of the square root of a divided by the square root of 1 minus a.
7. We’re defining a variable called d that is equal to R times c.
8. We’re returning d.
9. We’re defining a function called deg2rad that takes in a parameter called deg.
10. We’re returning deg times pi divided by 180.

Similar Posts