Calculate distance between two points in Leaflet

Taieb picture Taieb · Apr 2, 2017 · Viewed 21.3k times · Source

How do you calculate the distance between two markers in Leaflet-ionic2?

Couldn't figure out, I hope there is an Algorithme to do as soon as i select a marker it show me the distance between my location and the marker.

Thanks..

Answer

Gaurav Mukherjee picture Gaurav Mukherjee · Apr 4, 2017

You can use this function to find distance between 2 position.

function getDistance(origin, destination) {
    // return distance in meters
    var lon1 = toRadian(origin[1]),
        lat1 = toRadian(origin[0]),
        lon2 = toRadian(destination[1]),
        lat2 = toRadian(destination[0]);

    var deltaLat = lat2 - lat1;
    var deltaLon = lon2 - lon1;

    var a = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(deltaLon/2), 2);
    var c = 2 * Math.asin(Math.sqrt(a));
    var EARTH_RADIUS = 6371;
    return c * EARTH_RADIUS * 1000;
}
function toRadian(degree) {
    return degree*Math.PI/180;
}
var distance = getDistance([lat1, lng1], [lat2, lng2])

We are using this function in our library time-aware-polyline to encode lat lng info with timestamp.