JavaScript Calculate Distance Between Latitude Longitude Points


JavaScript Calculate Distance Between Latitude Longitude Points : Distance between two lat lon points can be calculated using the Haversine formula. Here in this tutorial we are going to explain how you can create a function to get the distance between two lat lon points. We are going explain this with example & online demo.


JavaScript Calculate Distance Between Latitude Longitude Points Formula

You can calculate distance between the latitude and longitude using the following formula-

Method 1 – Using Haversine Formula

Haversine formula is used to calculate distance between two points using the latitue and longitude-

JavaScript Calculate Distance Between Latitude Longitude Points Example:

<script type="text/javascript">
function getDistanceFromLatLonInKm(latitude1,longitude1,latitude2,longitude2,units) {
  var earthRadius = 6371; // Radius of the earth in km
  var dLat = deg2rad(latitude2-latitude1);  // deg2rad below
  var dLon = deg2rad(longitude2-longitude1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(latitude1)) * Math.cos(deg2rad(latitude2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = earthRadius * c; 
  var miles = d / 1.609344; 

if ( units == 'km' ) {  
return d; 
 } else {
return miles; 
}
}
</script>

Try it »

The above example will give you the distance between two latitude longitude points.

Method 2

You can also use the below method to get the distance between the lat, lon points –

JavaScript Calculate Distance Between Latitude Longitude Points Example:

<script type="text/javascript">
function getDistanceFromLatLonInKm(latitude1,longitude1,latitude2,longitude2,units) {
  var p = 0.017453292519943295;    //This is  Math.PI / 180
  var c = Math.cos;
  var a = 0.5 - c((latitude2 - latitude1) * p)/2 + 
          c(latitude1 * p) * c(latitude2 * p) * 
          (1 - c((longitude2 - longitude1) * p))/2;
  var R = 6371; //  Earth distance in km so it will return the distance in km
  var dist = 2 * R * Math.asin(Math.sqrt(a)); 
 document.getElementById("output").innerHTML = dist+"Km"; 
}
</script>

Try it »

The above example will give you the distance between two latitude longitude points. If you run the above example it will output something like this –

JavaScript Calculate Distance Between Latitude Longitude Points


Advertisements

Add Comment

📖 Read More