多点之间的最短距离

时间:2013-04-20 16:05:42

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

所以我想计算我的起点和多点之间的距离,而不是显示到这一点的最短路线,但它始终显示我的最后一点。这是我的distanceCal函数,它工作正常:

function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2 - lat1);  // deg2rad below
var dLon = deg2rad(lon2 - lon1);
var a =
  Math.sin(dLat / 2) * Math.sin(dLat / 2) +
  Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
  Math.sin(dLon / 2) * Math.sin(dLon / 2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c; // Distance in km
return d;
}

function deg2rad(deg) {
 return deg * (Math.PI / 180)
} 

这是我的点/长:

var dist = [
  [35.733972, -5.881999],
  [ 35.734077, -5.881033],
  [ 35.736898, -5.877771],
  [35.738396, -5.875154]
  ];

然后我的脚本显示方向:

function calcRoute() {
var start = new google.maps.LatLng(35.728329, -5.882750);
for (var i = 0; i < dist.length; i++)
{
    var dis = dist[i];
    //here i need something to choose the shortest route
    var min = Math.min(getDistanceFromLatLonInKm(35.728329, -5.882750, dis[0], dis[1]));
    var end = new google.maps.LatLng(dis[0], dis[1]);
}
    var request = {
        origin: start,
        destination: end,
        optimizeWaypoints: true,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

directionsService.route(request, function (response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
    }
});

}
google.maps.event.addDomListener(window, 'load', getMap);

所以,如果有人有任何想法或解决方案,我将非常感激。

2 个答案:

答案 0 :(得分:1)

以下代码使用Google geometry库来计算点之间的距离。距离存储在数组中,然后进行解析以找到最小距离。

我已经将数组从dist []更改为coords [],因为我们需要一个数组来保持距离dist []。

<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
 var coords = [
  [35.733972, -5.881999],
  [35.734077, -5.881033],
  [35.736898, -5.877771],
  [35.738396, -5.875154]
  ];
  var dist = [];//Array to hold distances
   function calcRoute() { {
      var start = new google.maps.LatLng(35.728329, -5.882750);
      for (var i = 0; i < coords.length; i++){
        var point = new google.maps.LatLng(coords[i][0],coords[i][1]);
        var distance = google.maps.geometry.spherical.computeDistanceBetween(start, point);
        dist.push(distance);
       }  
        var test = dist[0];
   var index = 0;
   for (var i = 1; i < dist.length; i++){
        if(dist[i] < test){
            test = dist[i];
            index = i;
        }
    }
   var end = new google.maps.LatLng(coords[index][0],coords[index][1]);

       // Apply the rest of your code here

答案 1 :(得分:0)

听起来你想在DirectionsServiceRequest中使用optimizeWaypoints:true:

  

optimizeWaypoints |布尔值|如果设置为true,DirectionService将尝试重新排序提供的中间航点,以最大限度地降低路线的总成本。如果优化了航点,请检查响应中的DirectionsRoute.waypoint_order以确定新的排序。

DirectionsResult

返回的每个leg of each route都包含距离和持续时间信息。