admin管理员组

文章数量:1397192

I have created a simple jsfiddle here using Google's Map Distance Matrix to determine the mileage between 2 points. This worked fine, but then I was interested in determining the mileage between more than 2 points. However I could not get very far with this, as I don't think I have implemented it correctly. Does anyone know how to add waypoints to Google's Distance Matrix in order to determine the best route/mileage between them by car? For example if I wanted to get from the The Underpass, Birmingham to 8 Shandon Close, Birmingham through a bunch of other places. My code has been included below:

var origin = "The Underpass, Marston Green, Birmingham, West Midlands B40 1PA, UK",
    destinations = ["8 Shandon Close, Birmingham, West Midlands B32 3XB, UK","2 The Osiers, Elford, Tamworth, Staffordshire B79 9DG, UK","170 Bells Lane, Birmingham, West Midlands B14 5QA, UK","246 Long Acre, Birmingham, West Midlands B7 5JP, UK","28 Cuthbert Road, Birmingham, West Midlands B18 4AG, UK"]
    service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix({
    origins: [origin],
    destinations: destinations,
    travelMode: google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false,
    unitSystem: google.maps.UnitSystem.IMPERIAL
},
callback);

function callback(response, status) {
    var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

    if (status == "OK") {
        orig.value = response.originAddresses[0];
        dest.value = response.destinationAddresses[0];
        dist.value = response.rows[0].elements[0].distance.text;
    } else {
        alert("Error: " + status);
    }
}

I have created a simple jsfiddle here using Google's Map Distance Matrix to determine the mileage between 2 points. This worked fine, but then I was interested in determining the mileage between more than 2 points. However I could not get very far with this, as I don't think I have implemented it correctly. Does anyone know how to add waypoints to Google's Distance Matrix in order to determine the best route/mileage between them by car? For example if I wanted to get from the The Underpass, Birmingham to 8 Shandon Close, Birmingham through a bunch of other places. My code has been included below:

var origin = "The Underpass, Marston Green, Birmingham, West Midlands B40 1PA, UK",
    destinations = ["8 Shandon Close, Birmingham, West Midlands B32 3XB, UK","2 The Osiers, Elford, Tamworth, Staffordshire B79 9DG, UK","170 Bells Lane, Birmingham, West Midlands B14 5QA, UK","246 Long Acre, Birmingham, West Midlands B7 5JP, UK","28 Cuthbert Road, Birmingham, West Midlands B18 4AG, UK"]
    service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix({
    origins: [origin],
    destinations: destinations,
    travelMode: google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false,
    unitSystem: google.maps.UnitSystem.IMPERIAL
},
callback);

function callback(response, status) {
    var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

    if (status == "OK") {
        orig.value = response.originAddresses[0];
        dest.value = response.destinationAddresses[0];
        dist.value = response.rows[0].elements[0].distance.text;
    } else {
        alert("Error: " + status);
    }
}
Share Improve this question asked Feb 24, 2015 at 17:14 methuselahmethuselah 13.2k53 gold badges177 silver badges333 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

From the documentation for the Distance Matrix

Google's Distance Matrix service putes travel distance and journey duration between multiple origins and destinations using a given mode of travel.

This service does not return detailed route information. Route information, including polylines and textual directions, can be obtained by passing the desired single origin and destination to the Directions Service.

If you need the distance between 2 places via a set of (less than 8) waypoints, use the directions service

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom: 7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
  calcRoute();
}

var origin = "The Underpass, Marston Green, Birmingham, West Midlands B40 1PA, UK",
  destinations = ["8 Shandon Close, Birmingham, West Midlands B32 3XB, UK", "2 The Osiers, Elford, Tamworth, Staffordshire B79 9DG, UK", "170 Bells Lane, Birmingham, West Midlands B14 5QA, UK", "246 Long Acre, Birmingham, West Midlands B7 5JP, UK", "28 Cuthbert Road, Birmingham, West Midlands B18 4AG, UK"]


service = new google.maps.DistanceMatrixService();

function calcRoute() {
  var waypts = [];
  for (var i = 1; i < destinations.length - 1; i++) {
    waypts.push({
      location: destinations[i],
      stopover: true
    });
  }
  var request = {
    origin: origin,
    destination: destinations[destinations.length - 1],
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

      orig.value = response.routes[0].legs[0].start_address;
      dest.value = response.routes[0].legs[3].end_address;
      var total_distance = 0.0;
      for (var i=0; i<response.routes[0].legs.length; i++) {
        total_distance += response.routes[0].legs[i].distance.value;
        }
      dist.value = total_distance +" meters";
    }
  });
}


google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px
}
#panel {
  position: absolute;
  top: 5px;
  left: 50%;
  margin-left: -180px;
  z-index: 5;
  background-color: #fff;
  padding: 5px;
  border: 1px solid #999;
<script src="https://maps.googleapis./maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>
<div id="mileage-details">Origin:
  <input id="orig" type="text" style="width:35em">
  <br>
  <br>Destination:
  <input id="dest" type="text" style="width:35em">
  <br>
  <br>Distance:
  <input id="dist" type="text" style="width:35em">
</div>

本文标签: javascriptAdding waypoints to Google Distance Matrix to determine mileageStack Overflow