在Gmaps Api中使用一个航点作为目的地

时间:2015-11-22 17:54:09

标签: api google-maps map-directions

我正在使用gmaps Api为必须访问市场列表(我的航路点)的人制定路线,以记录他们的股票。我使用用户的房屋位置作为路线的起源和市场的位置作为我的航点。问题是我不知道哪个路点是路由的目的地,因为我在调用方向服务时设置了属性optimization = true,但是api需要一个目的地来跟踪路由。

我需要的是一种告诉api使用我的优化路线的最后一个路点作为目的地的方法。

1 个答案:

答案 0 :(得分:0)

您可以向路线服务发出多个请求,其中一个请求每个可能的路点作为最终目的地,选择最短的结果距离。

proof of concept fiddle

代码段

var map;
var directionsServices = [];
var directionsDisplays = [];
// constant "start" address
var start = "Paramus, NJ";
// list of possible candidate destinations/waypoints (must be < 9)
var locations = ["67 E Ridgewood Ave, Paramus, NJ 07652",
  "450 Rochelle Ave, Rochelle Park, NJ 07662,",
  "720 River Rd, New Milford, NJ 07646",
  "280 Main St, New Milford, NJ 07646",
  "469 Passaic St, Hackensack, NJ 07601",
  "91 Broadway, Elmwood Park, NJ 07407",
  "206 Market St, Saddle Brook, NJ 07662"
];
var routes = [];

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  document.getElementById('info').innerHTML += "<u><b>intermediate results:</b></u><br>";
  getDirections(start, locations, map);
}
google.maps.event.addDomListener(window, "load", initialize);

function getDirections(start, waypoints, map) {
  var requests = [];
  var request = {
    origin: start,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };
  for (var j = 0; j < waypoints.length; j++) {
    var waypts = [];
    for (var i = 0; i < waypoints.length; i++) {
      if (i != j) {
        waypts.push({
          location: waypoints[i],
          stopover: true
        });
      }
    }
    requests[j] = {};
    requests[j].destination = waypoints[j];
    requests[j].waypoints = waypts;
    requests[j].origin = start;
    requests[j].optimizeWaypoints = true;
    requests[j].travelMode = google.maps.TravelMode.DRIVING;

    setTimeout(function(request, j) {
      sendDirectionsRequest(request, j, map);
    }(requests[j], j), 3000 * j);
  }
}

function sendDirectionsRequest(request, index, map) {
  var directionsService = new google.maps.DirectionsService();
  directionsServices.push(directionsService);
  directionsService.route(request, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      var route = response.routes[0];
      routes.push(route);
      var distance = 0;
      var duration = 0;
      for (var i = 0; i < route.legs.length; i++) {
        distance += route.legs[i].distance.value;
        duration += route.legs[i].duration.value;
      }
      route.distance = distance;
      route.duration = duration;
      route.index = index;
      document.getElementById('info').innerHTML += (routes.length - 1) + " dist:" + (route.distance / 1000).toFixed(2) + " km dur:" + (route.duration / 60).toFixed(2) + " min dest:" + index + " loc:" + locations[index] + " waypt order:" + route.waypoint_order + "<br>";
      if (routes.length == locations.length) {
        routes.sort(sortFcn);
        var directionsDisplay = new google.maps.DirectionsRenderer({
          map: map,
          polylineOptions: {
            strokeOpacity: 0.9,
            strokeWeight: 4,
            strokeColor: "black",
            zIndex: 10
          }
        });
        directionsDisplay.setDirections(response);
        directionsDisplay.setMap(map);
        document.getElementById('info').innerHTML += "<u><b>shortest result:</b></u><br>" + routes[0].index + " dist:" + (routes[0].distance / 1000).toFixed(2) + " km dur:" + (routes[0].duration / 60).toFixed(2) + " min dest:" + routes[0].index + " loc:" + locations[index] + " waypt order:" + routes[0].waypoint_order + "<br>";
      }
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

function sortFcn(a, b) {
  if (a.distance > b.distance) return 1;
  else if (a.distance < b.distance) return -1;
  else return 0;
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="info"></div>
<div id="map_canvas"></div>