How to calculate the distance between two points?

I have a function to calculate and latlng values, but how can I calculate the distance between the first and the last?

 function calculate() {
         //poo abbreviation for point of origin not poo=shit
         var poolat = locations[0].lat;
         var poolng = locations[0].lng;
         var destlat = locations[locations.length - 1].lat;
         var destlng = locations[locations.length - 1].lng;

      

+3


source to share


3 answers


There are two ways: you can use the Haversine formula, which requires a little more typing, or you can use the API.

Try the following in your calculate function

var distance = google.maps.geometry.spherical.computeDistanceBetween(
    new google.maps.LatLng(poolat, poolng), 
    new google.maps.LatLng(destlat, destlng)
);

      



console.log (distance);

Note:

The default distance is in meters.

+1


source


This question has already been answered: Calculate the distance between two latitude longitude points? (Haversine's formula)



Note that Haversine's formula assumes an ideal sphere, not a spheroid, which is earth.

+3


source


Try it. Built-in Math functions make it easy

function calculate() {
     //poo abbreviation for shit
     var poolat = locations[0].lat;
     var poolng = locations[0].lng;
     var destlat = locations[locations.length - 1].lat;
     var destlng = locations[locations.length - 1].lng;

     return Math.sqrt(Math.pow((destlat - poolat),2) + Math.pow((destlng - poolng),2))
}

      

0


source







All Articles