Distance Matrix with Waypoints

Using the distance matrix to find the shortest route through all the waypoints

by qhoc

HTML

<script src="http://maps.google.com/maps/api/js?sensor=false&amp;.js"></script>
<div id="results"></div>
<div id="map"></div>

CSS

#map {
    width: 450px;
    height: 400px;
}

JavaScript

var map;
var origin = "11 5th Ave, Seattle, WA 98121, USA"
var destinations = [
    "2033 Dorsett Village, Maryland Heights, MO 63043",
    "1208 Tamm Avenue, St. Louis, MO 63139",
    "55 E Brokaw Rd, San Jose, CA 95112, USA"];
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

function calculateDistances() {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: [origin], //array of origins
        destinations: destinations, //array of destinations
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, callback);
}

function callback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    } else {
        //we only have one origin so there should only be one row
        var routes = response.rows[0];               
        var sortable = [];
        var resultText = "Origin: <b>" + origin + "</b><br/>";
        resultText += "Possible Routes: <br/>";
        for (var i = routes.elements.length - 1; i >= 0; i--) {
            var rteLength = routes.elements[i].duration.value;
            resultText += "Route: <b>" + destinations[i] + "</b>, " + "Route Length: <b>" + rteLength + "</b><br/>";
            sortable.push([destinations[i], rteLength]);
        }
        //sort the result lengths from shortest to longest.
        sortable.sort(function (a, b) {
            return a[1] - b[1];
        });
        //build the waypoints.
        var waypoints = [];
        for (j = 0; j < sortable.length - 1; j++) {
            console.log(sortable[j][0]);
            waypoints.push({
                location: sortable[j][0],
                stopover: true
            });
        }
        //start address == origin
        var start = origin;
        //end address is the furthest desitnation from the origin.
     ...