Calculate Distance between markers

Asked

Viewed 1,323 times

0

Eai, well, I will try to be brief and clear, I would like to know how I can calculate the distance between markers, the markers are all already put on the map, but I need the code to calculate which one is closest to my location (I already know my location too). I count on you, I thank you in advance!

1 answer

1

Easy. Try on the Chrome console:

     /*
       Retorna distancia em metros
     */
    var haversine = function(lat1, lon1, lat2, lon2) {
        var deg2rad = 0.017453292519943295; // === Math.PI / 180
        var cos = Math.cos;
        lat1 *= deg2rad;
        lon1 *= deg2rad;
        lat2 *= deg2rad;
        lon2 *= deg2rad;
        var diam = 12742; // Diameter of the earth in km (2 * 6371)
        var dLat = lat2 - lat1;
        var dLon = lon2 - lon1;
        var a = ( (1 - cos(dLat)) +
                (1 - cos(dLon)) * cos(lat1) * cos(lat2)
        ) / 2;

        return diam * Math.asin(Math.sqrt(a)) * 1000;
    };

>haversine(-21.2332, -41.8744, -21.1800, -42.098)
>23922.44182687389

Browser other questions tagged

You are not signed in. Login or sign up in order to post.