3

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;
dbzabuse
  • 35
  • 5
  • Your post needs a bit more info to be answered. Are you looking for the straight line distance between two points (as the crow flies)? – Tom Apr 21 '17 at 17:03
  • Yes, aerial distance, nevermind I got it working, thank you anyway sir – dbzabuse Apr 21 '17 at 17:32

3 Answers3

3

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.

Community
  • 1
  • 1
jchen123
  • 61
  • 7
1

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.

dbzabuse
  • 35
  • 5
Aldin Juko
  • 106
  • 1
  • 8
0

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