获得两点之间的最短距离

时间:2017-06-20 09:49:27

标签: javascript angularjs google-maps google-maps-api-3

我需要计算两点之间的最短距离。我正在使用以下功能来实现这一点。

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

这使得 33.77 km 作为距离。但根据google maps,上述点之间的最短距离应 45.0 km

我怎么能得到那个价值? ( 45.0 km

这是jsfiddle link

2 个答案:

答案 0 :(得分:2)

球面距离是a-b的直线距离(如苍蝇一样)

您发布的Google地图链接显示了一条45公里长的街道。

编辑:要获得最短的街道距离,您需要查看谷歌地图方向API而不是球形方法: https://developers.google.com/maps/documentation/directions/intro

答案 1 :(得分:1)

要获得道路距离,您可以使用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;
});

您可以在此处找到图书馆:https://maps.google.com/maps/api/js?sensor=false&libraries=geometry