Distance in meters between two coordinates using Javascript

Asked

Viewed 5,270 times

0

Can you help me solve a problem? I need to calculate the distance in meters between two GPS coordinates. But I need to do it using pure Javascript.

The context of this is that my application needs to validate the coordinated registration of a client with the coordinate of marking at the time of data collection. For example:

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

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

  • A good part of the formula I put here: https://answall.com/a/214587/64969; the constant relative to the radius of the Earth needs to be put and perhaps normalize z =]

  • Welcome Genilson Soares, take a tour of the site starting with https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079 and read this post https://answall.com/help/mcve

1 answer

3

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 another calculation here

That one link besides javascript has in several other languages

  • I calculated on 2 different sites and the result was the same: 22.6KM

  • @DVD Then the answer formula is correct, only two decimal places are left

  • Yeah, but leave it like that 'cause he wants it in yards.

  • In fact, it would be better to eliminate the decimals.

  • @Dvd too many decimal house 22590.197662552924 if it marks as accepted do to round rs :)

  • console.log((getDistanceFromLatLonInKm({lat: -23.522490, lng: -46.736600},{lat: -23.4446654, lng: -46.5319316})/1000).toFixed(1)); gives 22.6 rs

Show 1 more comment

Browser other questions tagged

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