Distance in meters between two coordinates using JavaScript

0

Can you help me with solving a problem? I need to calculate the distance in meters between two GPS coordinates. But I need to do this using pure JavaScript.

The context of this is that my application needs to validate the coordinate of a customer's register with the marking coordinate at the moment of data collection. For example:

  • Coordinate customer registration: -23.522490; -46.736600
  • Coordinate marking: -23.4446654; -46.5319316

Compare the two coordinates and return the distance between them in meters.

    
asked by anonymous 01.11.2017 / 02:37

1 answer

2

function getDistanceFromLatLonInKm(position1, position2) {
    "use strict";
    var deg2rad = function (deg) { return deg * (Math.PI / 180); },
        R = 6371,
        dLat = deg2rad(position2.lat - position1.lat),
        dLng = deg2rad(position2.lng - position1.lng),
        a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
            + Math.cos(deg2rad(position1.lat))
            * Math.cos(deg2rad(position1.lat))
            * Math.sin(dLng / 2) * Math.sin(dLng / 2),
        c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return ((R * c *1000).toFixed());
}

var distancia = (getDistanceFromLatLonInKm(
   {lat: -23.522490, lng: -46.736600},
   {lat: -23.4446654, lng: -46.5319316}
));

console.log(distancia);

See other calculations here

This link besides javascript has in several other languages

    
01.11.2017 / 03:04