CommuteTest2
Using only Distance Matrix
by dannyywhite
HTML
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry&.js"></script>
<div id="map"></div>
<div id="results"></div>
CSS
#map {
width: 450px;
height: 400px;
}
JavaScript
var map;
var geocoder;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var latCenter = 51.518742;
var lonCenter = -0.118777;
var radius = 1200;
var numberedMarker = "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=___|FE6256|000000";
var callbackCount = 0;
function calculateDistances(origin, destinations) {
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];
//need to find the shortest
var lowest = Number.POSITIVE_INFINITY;
var tmp;
var shortestRouteIdx;
var resultText = "Possible Routes: <br/>";
//for (var i = routes.elements.length - 1; i >= 0; i--) {
for(var i = 0; i < routes.elements.length -1; i++) {
callbackCount = callbackCount + 1;
var callbackCountStr = callbackCount.toString();
tmp = routes.elements[i].duration.value;
resultText += callbackCountStr +") " + response.destinationAddresses[i] + ": " + tmp/60 + "<br/>";
/*if (tmp < lowest) {
lowest = tmp;
shortestRouteIdx = i;
}*/
//log the routes and duration.
$('#results').html(resultText);
}
//get the shortest route
var shortestRoute = destinations[shortestRouteIdx];
//now we need to map the route.
...