Google Distance Matrix
December 17, 2011
I had a page, showing a google map, that showed the bands within a particular radius of a point along with their "crow-flies" distance from that point. I also wanted to show driving distance and time, and google provide functionality to allow this information to be obtained.
Note that you need to show a google map to use this functionality - it's in the terms and conditions.
JavaScript
First we have a callback function which will be used to show the results of the distance matrix in a HTML table.
function renderDrivingDistances(pResponse, pStatus) { for(var i=0; i<pResponse.rows[0].elements.length; i++) { var lBandDestination = pResponse.rows[0].elements[i]; $('#band_result' + i + " td.driving_distance").html(lBandDestination.distance.text + "les"); $('#band_result' + i + " td.driving_time").html(lBandDestination.duration.text); } }
Next, we call the distance matrix code, passing in an origin, in this case using Django template variables Latitude
and Longitude
. We also pass in the closest 25 bands "as the crow flies" - these are in the Django template variable BandsDrivingDistance
. The API limits you to 25 destinations.
// call distance matrix functionality var gDistanceMatrix = new google.maps.DistanceMatrixService(); gDistanceMatrix.getDistanceMatrix({ origins: [new google.maps.LatLng({{Latitude}}, {{Longitude}})], destinations: [ {% for band in BandsDrivingDistance %} new google.maps.LatLng({{band.latitude}}, {{band.longitude}}), {% endfor %} ], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERIAL }, renderDrivingDistances);
Note also that we have specified TravelMode.DRIVING
for driving distances, and UnitSystem.IMPERIAL
to get the results in miles.