dbzabuse
dbzabuse

Reputation: 35

How do I calculate the distance between two points?

I have a calculate function and the latlng values but how do 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;

Upvotes: 3

Views: 1188

Answers (3)

Aldin Juko
Aldin Juko

Reputation: 106

There is 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 value of the distance is in metres.

Upvotes: 1

Try this. The built in Math functions make it much easier

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))
}

Upvotes: 0

jchen123
jchen123

Reputation: 61

This question has already been answered here: Calculate distance between two latitude-longitude points? (Haversine formula)

Note that the Haversine formula assumes a perfect sphere, not a spheroid which is what the earth is.

Upvotes: 3

Related Questions