0

I need to calculate shortest distance between two points. I am using below function to achieve that.

var p1 = new google.maps.LatLng(6.71532762,80.06215197);
var p2 = new google.maps.LatLng(6.93234287,79.84870747);

var distance = document.getElementById('distance');
distance.innerHTML = distance.innerHTML+calcDistance(p1, p2);

//calculates distance between two points in km's
function calcDistance(p1, p2) {
  return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);  
} 

This gives 33.77 km as distance. But according to google maps, shortest distance between above points should be 45.0 km.

How could I get that value? (45.0 km)

Here is the jsfiddle link.

Bishan
  • 15,211
  • 52
  • 164
  • 258
  • 1
    Note that the method you're calling is "google.maps.geometry. **spherical** .computeDistanceBetween" which I suspect is the great circle distance between the two points (i.e. shortest distance around the globe). – RobG Jun 20 '17 at 09:55
  • I measured the distance in Google Maps myself and got **~33.7 km** as a result. Edit: I suppose you got the **45 km** from the distance on road. This is not the function you are looking for if you want to measure distance by road. [See this link for that](https://developers.google.com/maps/documentation/javascript/direction) –  Jun 20 '17 at 09:58
  • 1
    Computing spherical distance != distance traveled via roads. Please specify what you need. –  Jun 20 '17 at 10:07

2 Answers2

2

The spherical distance is the distance in a straight line from a - b (as the bird flies)

The google maps link you posted shows a street that is 45km long.

EDIT: To get the shortest street distance you need to have a look into the google maps directions API instead of the spherical method: https://developers.google.com/maps/documentation/directions/intro

Fabwoofer
  • 111
  • 4
1

To get the road distance, you can use google.maps.DirectionsService() :

var p1 = new google.maps.LatLng(6.71532762, 80.06215197);
var p2 = new google.maps.LatLng(6.93234287, 79.84870747);

function getShortestDistance(p1, p2) {
  return new Promise(function(resolve, reject) {
    var request = {
      origin: p1,
      destination: p2,
      travelMode: google.maps.TravelMode.DRIVING,
      provideRouteAlternatives: true
    };
    new google.maps.DirectionsService().route(request, function(response, status) {
      var minRoute = null;
      for (var i = 0; i < response.routes.length; i++) {
        if (minRoute === null || response.routes[i].legs[0].distance.value < minRoute.legs[0].distance.value) {
          minRoute = response.routes[i];
        }
      }
      resolve(minRoute);
    });
  });
}

getShortestDistance(p1, p2).then(function(result) {
  document.getElementById('distance').innerHTML = 'Distance : ' +     result.legs[0].distance.text;
});

You can find the library here : https://maps.google.com/maps/api/js?sensor=false&libraries=geometry

Rylyn
  • 333
  • 3
  • 10