Friday, 10 February 2017

Calculate Distance through Haversine formula.

What do we need Haversine's Formula?
Just  to calculate the distance between longitude & latitude coordinates of two given places.



$('some_element').click(function(){
    var loc1 = [lat, lon] // It Specify Longitude and latitude
    var loc2 = [lat, lon] // It Specify Longitude and latitude

    var lat1 = loc1[0], lon1 = loc1[1];
    var lat2 = loc2[0], lon2 = loc2[1];
    var earth = 6371 // Earth's Radius in Kilometre

    var dLat = (lat2-lat1) * Math.PI / 180;
    var dLon = (lon2-lon1) * Math.PI / 180;
    var nlat1 = (lat1) * Math.PI / 180;
    var nlat2 = (lat2) * Math.PI / 180;

    // Calculation
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(nlat1) * Math.cos(nlat2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = earth * c;
    var distance = Math.round(d*Math.pow(10,2)) / Math.pow(10,2); //Round off to 2 decimal places
    alert(distance);
});

0 comments:

Post a Comment