How to calculate driving distance with Google Maps API
Reading time: About 6 minutes
Once upon a time I wrote How to calculate distance with javascript and Google Maps API. This article showed my readers how to calculate the straight line distance between two addresses. It turns out that people really wanted the driving distance between two addresses. I get an e-mail about this about once a day.
Today I will finally provide the long–awaited much–anticipated tutorial: how to calculate driving distance between two addresses using javascript and google maps API.
What I’ve built for you here is a javascript/Google Maps-driven web app that will take two fuzzy locations/addresses, turn them into full addresses and coordinates, and calculate the driving distance in miles and kilometers between them. So again, input two fuzzy address and output full addresses and distance. Sounds like a win for the you and your users.
Let’s step through the code to see how I did it. If you don’t want to learn about the code, go ahead and see the end result with source code.
The HTML
The HTML is pretty basic, but there are a few things to note:
- Change the google maps API key to your own. Mine will not work on your domain. If you don’t have one, grab your Google Maps API key for free.
- The form submits to a function named
showLocation()and the body loads with a function namedinitialize(). We’ll build these in the next section.- The empty
<p id="results">element at the bottom of the HTML is used to output the results.- Advanced JS devs: This uses inline javascript events and javascript in the
<head>for the sake of simplicity. If you know how to move javascript externally, that is a better way to go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="robots" content="noindex,follow" /> <title>Calculate driving distance with Google Maps API</title> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script> <!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html --> </head> <body onload="initialize()"> <form action="#" onsubmit="showLocation(); return false;"> <p> <input type="text" name="address1" value="Address 1" /> <input type="text" name="address2" value="Address 2" /> <input type="submit" value="Search" /> </p> </form> <p id="results"></p> </body> </html>Now let’s look at the javascript, where the real magic happens. We’ll look at the javascript in more detail than we did with the HTML.
Stepping through the Javascript
If you’d like skip the steps to the complete javascript code
First we’ll define global variables used in more than one function
1 var geocoder, location1, location2, gDir;Next we’ll define our
<body> onloadevent which prepares the Google Maps API for our requests and prepares to calculate the distance. Here’s the steps it goes through:
- Line 1 & 2: Assign Google’s geocoder (GClientGeocoder()) and Google’s directions API (GDirections()) to global variables
- Line 3: Add a “load” even listener to the directions API. Which means, when Google finishes calculating the driving distance, the following steps are performed:
- The driving distance is calculated from gDir.getDistance().meters in miles and kilometers
- The address and distance information is printed to the screen in to #results
<div>
1 2 3 4 5 6 7 8 9 function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)'; }); }Next we’ll define
showLocation(), which is called when the user submits the form with the two fuzzy addresses. Here’s the steps it goes through:
- Attempt to get the first location’s information from the Google Maps API;
- Put the first location’s information including lat, lon, and full address into an object called
location1;- Attempt to get the second location’s information from the Google Maps API;
- Put the second location’s information including lat, lon, and full address into an object called
location2;- Use Google’s directions API as
gDirto “load” the driving distance (which triggers the “load” event listener we defined above)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 function showLocation() { geocoder.getLocations(document.forms[0].address1.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].address2.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); }Completed Javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 var geocoder, location1, location2, gDir; function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)'; }); } function showLocation() { geocoder.getLocations(document.forms[0].address1.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].address2.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); }Advanced javascript developers: If you want to, feel free to put the above code into an external javascript file.
All of the source code together in one working file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> <meta name="robots" content="noindex,follow" /> <title>Calculate driving distance with Google Maps API</title> <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script> <!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html --> <script type="text/javascript"> var geocoder, location1, location2, gDir; function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceKilometers = gDir.getDistance().meters / 1000; document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)'; }); } function showLocation() { geocoder.getLocations(document.forms[0].address1.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].address2.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); } </script> </head> <body onload="initialize()"> <form action="#" onsubmit="showLocation(); return false;"> <p> <input type="text" name="address1" value="Address 1" /> <input type="text" name="address2" value="Address 2" /> <input type="submit" value="Search" /> </p> </form> <p id="results"></p> </body> </html>The end result
Your hard work has paid off! See the end result with source code
I’ve written quite a bit about geolocation and Google Maps API. If this is a topic that interests you, subscribe to my blog. If you use this, let me know how it works for you by leaving a response. Thank you!
Google Terms of Service Warning: According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API.
94 comments skip to comment form
user said— 20 hours later
Brian Cray said— 23 hours later
Mick said— 2 days later
Brian Cray said— 2 days later
jay said— 1 week later
jay said— 1 week later
Mohamed Jama said— 1 week later
Myfacefriends said— 1 week later
Brian Cray said— 1 week later
Jeremy Akers said— 2 weeks later
Brian Cray said— 2 weeks later
phutrek said— 3 weeks later
Vaibhav Kotalwar said— 3 weeks later
sameer said— 1 month later
Brian Cray said— 1 month later
sameer said— 1 month later
Brian Cray said— 1 month later
idev said— 1 month later
Busman said— 1 month later
Adrian said— 2 months later
Busman said— 2 months later
Busman said— 2 months later
Noman said— 2 months later
Adibi said— 2 months later
Mark said— 2 months later
Adibi said— 2 months later
Noman said— 2 months later
sameer said— 2 months later
Brian Cray said— 2 months later
sameer said— 2 months later
Ingo said— 2 months later
Ingo said— 2 months later
Noman said— 2 months later
Josh said— 2 months later
Nommi said— 3 months later
Raj said— 3 months later
Raj said— 3 months later
Jarred Suisman said— 3 months later
SV said— 3 months later
Brian Cray said— 3 months later
Raj said— 3 months later
SV said— 3 months later
Raj said— 3 months later
Roland said— 3 months later
Kim said— 4 months later
Roland said— 4 months later
Ravi said— 4 months later
Sid said— 4 months later
Pablo said— 4 months later
Phil Gill Purple Chilli Design said— 4 months later
Stefan said— 4 months later
malick mbaye said— 4 months later
Zena said— 4 months later
Punit Naker said— 4 months later
aaaDesigns said— 4 months later
Gary said— 4 months later
ben said— 5 months later
Luca said— 5 months later
JOhn said— 5 months later
bill said— 6 months later
Jessica Izaguirre said— 6 months later
J3 said— 6 months later
Brian Cray said— 6 months later
Horla said— 6 months later
Björn said— 6 months later
Bill said— 6 months later
David said— 6 months later
Jarred said— 6 months later
David said— 6 months later
Chris said— 7 months later
James said— 7 months later
Steve said— 7 months later
Daniel said— 7 months later
strangesoul said— 9 months later
Karel said— 9 months later
dominique said— 9 months later
warxsg said— 10 months later
Rafiq said— 11 months later
Will said— 11 months later
sivamyneni said— 11 months later
kumar said— 11 months later
Ryan said— 11 months later
Hiral Vyas said— 11 months later
Prajeevan said— 11 months later
Mark said— on June 23, 2009 later
Praveen Aithal H said— on June 23, 2009 later
Noman said— on June 23, 2009 later
Praveen Aithal H said— on June 23, 2009 later
Noman said— on June 23, 2009 later
Jerome Gaynor said— on June 23, 2009 later
Michelle said— on June 23, 2009 later
ali said— on June 23, 2009 later
Uldis said— on June 23, 2009 later
Uldis said— on June 23, 2009 later
Respond to this post—