Although this is quite a common question, the majority of tutorials seem to be over-complicating the solution which may confuse people who are new to the Google Maps API. This tutorial is designed to show you an easy way to geocode 2 addresses and get the driving distance between them.
We are going to base our app off the directions-simple.html sample that Google provides. We only need to change a few things to make it display the driving distance.
The first thing we’ll do is create the HTML file. You can use the following code as a guide:
<html>
<head>
<title>Distance Calculator</title>
<style type="text/css">
#map_canvas {
height: 100%;
}
</style>
</head>
<body>
<div>
<p>
<label for="start">Start: </label>
<input type="text" name="start" id="start" />
<label for="end">End: </label>
<input type="text" name="end" id="end" />
<input type="submit" value="Calculate Route" />
</p>
<p>
<label for="distance">Distance (km): </label>
<input type="text" name="distance" id="distance" readonly="true" />
</p>
</div>
<div id="map_canvas"></div>
</body>
</html>
Next, we’ll add the map to the page. Include the following 2 lines in your head tag:
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Then add a script tag to your head with the initialize function to set up the map:
<script type="text/javascript">
var directionDisplay;
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var melbourne = new google.maps.LatLng(-37.813187, 144.96298);
var myOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: melbourne
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
}
</script>
Finally, add the initialize function to the body onload, like so:
<body onload="initialize()">
If you load up your page, you should see a nice big Google map that doesn’t do much. Let’s change that.
Add a new variable called directionsService and a function called calcRoute() to your script, like so:
var directionsService = new google.maps.DirectionsService();
function calcRoute() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
Then change your submit button to call the function:
<input type="submit" value="Calculate Route" onclick="calcRoute()" />
If you save and reload your page, you should be able to enter 2 locations and the Google Maps API will geocode them and display the route on the map.
But of course, what you’ve really been waiting for is to get the distance of the trip. Let’s do it!
Inside the calcRoute() function, add a new variable called distanceInput (add it under the existing variables):
var distanceInput = document.getElementById("distance");
Last but not least, add the following line of code inside the directionsService response’s anonymous function (add it under the “directionsDisplay.setDirections(response);” line):
distanceInput.value = response.routes[0].legs[0].distance.value / 1000;
Save and reload your page. When you click Calculate Route, not only will the route be shown on the map, but the distance will be calculated too. Congratulations! If your code doesn’t seem to be working, you can view my working example at http://www.christianvarga.com/driving_distance.html to see what went wrong.
Let’s quickly discuss what we’re actually doing here so we can understand why we refer to the response like this.
The directions result object we receive from Google contains a routes array. Multiple routes can be returned if a request is sent with the provideRouteAlternatives field set to true (this is set in the request parameters), but this field defaults to false, and because we don’t set it, we are only ever dealing with one route so we refer to routes[0].
Inside the routes array is another array called legs, which contains details relating to each leg of the journey. A leg is defined as the trip from one waypoint to another. Waypoints can be set in the request parameters (these force the route to pass through the waypoint), however because we don’t set any waypoints, there is only one leg in the journey which is from the start location to the end location, so we refer to legs[0].
Finally, each leg of the journey contains a distance field, which you can either get the value of (in metres) by referring to .value, or you can get a textual representation in the locale’s units by referring to .text. I prefer to get the exact value in metres and then perform my own calculation (divide by 1000) to convert it into kilometres, so I call distance.value / 1000.
There’s a lot more to the Google Maps API, to get the most out of it you can have a look at the directions request/response documentation at http://code.google.com/apis/maps/documentation/javascript/services.html#Directions. This should get you started with extending the functionality of our little app.
If you have any questions or comments, please don’t hesitate to leave them below.