Although this is quite a common question, the majority of tutorials (as of 2010, the initial post date) seem to be overcomplicating the solution. This post is designed to show you an easy way to geocode 2 addresses and get the driving distance between them.
The Directions API makes this so simple, it hurts.
First, you’ll need to include the Maps API. It doesn’t get any easier than this.
Then, in your JS, instantiate the DirectionsService API, build a request object (which handily takes a fuzzy address and geocodes it, so you can enter a city, country, landmark, full addresses etc), and build the route.
If the request works, you’ll get a response object back. If the request fails, a kitten dies. So, for the love of kittens, please use valid destinations.
response.routes[0].legs[0].distance.value returns the distance in metres. If you’re bad with maths, divide by 1000 to get the distance in kilometres. If you’re bad with maths and you live in a country that’s determined to use units that make no sense, divide by 1609.34 to get the distance in miles, then go and sit in the corner and think about what you’ve done.
The code works and you probably don’t care why. But if you do, here’s what we’re doing.
The response object we receive from Google contains a routes array. Multiple routes can be returned if a request is sent with the provideRouteAlternatives property set to true (you would set this in the request object). This field defaults to false, and because we don’t set it, we’re only ever dealing with one route, so we refer to routes[0].
Each route contains a legs array. A leg is defined as the trip from one waypoint to another. Waypoints can be set in the request object (these force the route to pass through the waypoint, for example Melbourne to Sydney via Canberra). Because we don’t set any waypoints, there’s only one leg in the journey, so we refer to legs[0].
If you still haven’t been able to get this code working, and you’re looking for that delicious demo source code, look no further. You can see a working implementation here: https://christianvarga.com/driving_distance.html
If this post has helped you out, feel free to consider throwing a small donation my way.
Comments are closed.
47 comments
dear Guys,
i Know this is bit delay…
i modified the multiple select boxes to multiple check boxes… If u have time try this code…!!!
Waypoints in directions
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
//var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var lanka = new google.maps.LatLng(7.8772157,80.7003428);
var mapOptions = {
zoom: 7,
center: lanka,
mapTypeId: google.maps.MapTypeId.HYBRID,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
}
map = new google.maps.Map(document.getElementById(‘map-canvas’), mapOptions);
directionsDisplay.setMap(map);
}
function calcRoute() {
//alert(“test”);
var start = document.getElementById(‘start’).value;
var end = document.getElementById(‘end’).value;
//alert(start);
var waypts = [];
// var checkboxArray = document.getElementsByName(‘city’);//(‘waypoints’);
var checkboxArray = new Array();//new Array();
//alert(checkboxArray);
$(“.waypoints:checked”).each(function(index, element) {
checkboxArray[index] = $(this).val();
});
//alert(checkboxArray.length);
//alert(checkboxArray[1]);
for (var i = 0; i < checkboxArray.length; i++) {
waypts.push({
location:checkboxArray[i],
stopover:true});
}
//alert("sdgrs");
//var checkboxArray = document.getElementsByClassName('waypoints');
//var checkboxArray = document.getElementsByClassName('waypoints');
//alert(checkboxArray.length);
/*for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].checked == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}*/
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += 'Route Segment: ‘ + routeSegment + ‘‘;
summaryPanel.innerHTML += route.legs[i].start_address + ‘ to ‘;
summaryPanel.innerHTML += route.legs[i].end_address + ”;
summaryPanel.innerHTML += route.legs[i].distance.text + ”;
}
}
});
}
google.maps.event.addDomListener(window, ‘load’, initialize);
Start:
Colombo<!–
Boston, MA
New York, NY
Miami, FL–>
Waypoints:
(Check for multiple selection)
<!–
Kaluthata
Negombo
Ratnapura
Galle
Matara
Batticaloa
Trincomalee
Kandy
–>
<!–
Colombo–>
Kaluthata
Negombo
Ratnapura
Galle
Matara
Batticaloa
Trincomalee
Kandy<!–
Anuradhapura–>
End:
Anuradhapura<!–
Seattle, WA
San Francisco, CA
Los Angeles, CA–>
thnks
Great work !! Thanks . But suppose I wish to determine distance for multiple locations from a starting point , can you please suggest me about it?? Thanks in advance.
You can do that using Waypoints: https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints
Thank you very much. Works great and helped me a lot to understand it. You are great.
Hi Christian, I tried your code & found working fine. Thanks Bro. But I have a serious problem. I can’t find any solution. Plz help if you can. Problem is – Suppose, I start driving from my home(A) to office(Z). by using your code, I can calculate total driving distance of two points A to Z is 4.54 Km. But from my home (A), I went to my friend’s house (B), distance A to B is 1.15 Km, then from point (B), I went my Client’s Office (C), distance B to C is 3.74 Km & finally from point (C), I went my office (Z), distance C to Z is 2.33 Km. My path is A > B > C > Z & distance covered total is 1.15+3.74+2.33 = 7.22 Km. How can I calculate this travel path using Google map ? (plz don’t tell to calculate separately like A>B, B>C, Z>C). PLZ HELP !!!
You can do that using Waypoints. You can find further information in Google’s documentation: https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints.
Thanks for your suggestion. I want to take some of your busy time. Plz read….
My company has a customized VTS (Vehicle Tracking Service) solution, which we assembled here in Bangladesh. I am the web application developer and front-end developed using HTML, CSS, JS, PHP, MySql. Recently one of our client requested us for some requirement. They need total distance covered by every vehicle day-wise. So that, after every 30days, they can calculate the total distance and can change engine oil on that notification. Thats why I need this on php to save in the database. Will you plz guide me or code for me ? My company will pay you for this. If yes, plz response. I will discuss some issues later. Thanks.
Are the vehicles tracked via GPS? This would allow you to get a very accurate measure of the distance travelled without relying on Google Maps. You could store the latlng every 10 seconds (or so), then at the end of the day, add up the distance between all the latlng points (which can be done mathematically: http://www.movable-type.co.uk/scripts/latlong.html). This would be very accurate. You could even look at how Uber tracks vehicles as an example. If you use Google Maps, the results will be wildly inaccurate – what if someone takes a different route, or doesn’t track one of the trips? There are many issues with this approach, if the data needs to be reliable then I wouldn’t recommend the use of Google Maps. Unfortunately I can’t help you build a solution, I think it would be better if you found a developer in Bangladesh who can come on site and build the solution with you in person.
Thanks again for your valuable suggestion. I already tried some codes which provide me AIR distance between two points, not travled route distance. & Google Way-points had request/query limitation. grrrrr…..
Hi, Christian, i am trying out your code (i am very new to programming), but the map does not appear in the browser, possible to point out my mistake? thanks a lot
loaded the screen shot of the code for your reference. many thanks!
Hi Henry. I appreciate that you’re new to this, but sending me a screenshot of your code makes it really hard for me to debug. I can’t see the full document, I can’t copy/paste the code (so I can’t automatically detect syntax errors), I can’t run it… Basically all I can do is read your code line-for-line to try and find any errors, which is extremely time consuming on my behalf.
You need to start using tools such as jsFiddle or http://gist.github.com to send code snippets so that it’s easier for people to help you out.
You also need to check your console for errors, which usually highlights an issue when an entire script fails to work. I believe Internet Explorer has one: http://stackoverflow.com/questions/2656730/internet-explorer-console, however I would highly recommend switching to Chrome instead.
Hi Christian, i found the problem! now the map loads! thanks so much for giving me some direction! just a question: I change the “map_canvas” to “map-canvas” then it works, why so?
Henry, I hate to sound like a broken record, but without being able to see your full code then I can’t tell you what’s going on. Perhaps in your HTML, you’ve created a div with an ID of map-canvas instead of map_canvas (eg: ). But that part of your HTML cannot be seen in the screenshots you sent through, therefore I can’t know for sure – it’s just an assumption. Your call to document.getElementById MUST match the ID of the element you create.
Okay, got you, thanks for your time, i will follow what you suggested next time to make it easy for you to guide me (like using jsFiddle), thank you so much again and have a good day!
No worries, did you check the ID of your HTML element to see if it was map-canvas?
i have the same problem all i can see is the html session but the java wouldn’t work. Need some help please.
I provided a link to a working demo in my article, you can find it here: https://christianvarga.com/driving_distance.html. You need to look at that, then look at your own code to figure out where you went wrong. I can’t help you any further because you haven’t provided any code or explained your issue. I’m not a mind reader; saying “it doesn’t work” doesn’t give me any information that I can use to help you. Please read the following article: http://mattgemmell.com/what-have-you-tried/
Christian its very good code actually its woking fine , but small favour , in auto complete i need places within a country like, if its has country limit , very much fine. and thank you soo much
Autocomplete is out of the scope of my blog post. Google has plenty of examples demonstrating how to set up autocomplete, I’d suggest starting there: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
thanks a lot
hey Christian thank you a lot for the help. bas i would like to know should the address be entered in a certain way?
Hey Amr, the address does not have to be entered in a certain way. Google parses the address using its fuzzy algorithm, so you can type full addresses like “123 Test Street, Richmond, Victoria, Australia”, or a city such as “Melbourne”. Either will work.
Hola Christian,
Script is perfect thank you.
I want to ask another thing, can we choose the destinations by clicking on the? can you help?
*clicking on the map
It’s pretty simple, did you have a look at the API reference? You can listen for a click event on the map which returns the latlng of the clicked location. See here: https://developers.google.com/maps/documentation/javascript/examples/event-arguments. So using that, you can place a marker, and put the location into one of the text boxes. I made a very simple demo here: http://jsfiddle.net/ku5tf57u/
Hi Christian
This is a brilliant script – but is there a way I can pass the javascript var distanceInput into a php variable so I can enter it into a database ?
Yes, you would need to set up a separate PHP script then use ajax to send the distance to your PHP script for parsing. It’s a bit out of the scope of this post, but there is plenty of information out there: https://www.google.com.au/?gws_rd=ssl#q=send+javascript+variable+to+php+ajax
sir,how the automatic name come.like we want patiala(a city name)..and if we type a pat(whole patiala come)..and ur api or coding can give another path…how?
You probably want to take a look at the Places API Autocomplete: https://developers.google.com/places/documentation/autocomplete. They have plenty of working examples & code snippets in their documentation.
This is a great script, thanks a lot
Thank you so much for this! I’ve been trying to create a freight calculator based on distance, & draw a map on clicking a point from source to destination.could you help me to sort out this problem
Great. I was searching for this from 4 hours. Thanks
Great advice, I have been using a south african tool http://www.DistanceCalculator.co.za, should help your readers.
Great work my friend! Is there supposed to be a google api key somewhere in the code? Anonymous requests?
The API key isn’t actually required, Google just recommends using it. You can see my demo working here. That’s using an older version of the API (as this post was written in 2010), but v3 doesn’t require an API key either.
Thanks for posting this awesome tutorial 🙂
Thank you so much for this! I’ve been trying to create a delivery fee calculator based on distance, and I’ve looked all over the place trying to find something simple like your example that I could start with. It should work out perfectly. Thanks for sharing!
Glad it helped you out!
very good
I am trying to implement this code on my page but it does not load the map or work as your example does. I copied the script as is only adding my API key. what could be the problem.
I have it posted at the site below:
http://www.dfwtaxiservices.info/FareEstimate/DistCalcEXMP2.html
The very first step in debugging any javascript application is to check the console for errors. In your example, the console logs an error saying that the maps api js file can’t be loaded. A quick check on the URL shows that you’ve spelt the URL incorrectly; the URL you’ve put is maps.googleapis.com/maps/apis/js, yet it should be maps.googleapis.com/maps/api/js. You’ve got an extra ‘s’ on the end of the word ‘api’. If you fix this, the API load and you’ll get a bit further.
Thanks for the useful script. This is a real person unlike the comments below.
Thank you for posting this, it was quite helpful and told a lot
When I attended the King after my recovery, to return him thanks for his favors, he was pleased to rally me a good deal upon this adventure. He asked me what my thoughts and speculations were while I lay in the monkey’s paw, how I liked the victuals he gave me, his manner of feeding, and whether the fresh air on the roof had sharpened my stomach. He desired to know what I would have done upon such an occasion my own country. I told his Majesty that in Europe we had no monkeys, except such as were brought for curiosities from other places, and so small that I could deal with a dozen of them together, if they presumed to attack me. And as for that monstrous animal with whom I was so lately engaged (it was indeed as large as an elephant), if my fears had suffered me to think so far as to make use of my hanger (looking fiercely and clapping my hand upon the hilt as I spoke) when he poked his paw into my chamber, perhaps I should have given him such a wound, as would have made him glad to withdraw it with more haste than he put it in. This I delivered in a firm tone, like a person who was jealous lest his courage should be called in question. However, my speech produced nothing else besides a loud laughter, which all the respect due to his Majesty from those about him could not make them contain. This made me reflect how vain an attempt it is for a man to endeavor doing himself honor among those who are out of all degree of equality or comparison with him. And yet I have seen the moral of my own behavior very frequent in England since my return, where a little contemptible varlet, without the least title to birth, person, wit, or common sense, shall presume to look with importance, and put himself upon a foot with the greatest persons of the kingdom.
I ripped the lid off of a tin, and forced the chunk of pink meat down my throat in a single push, barely bothering to chew or taste. The next three tins went down the same way. Finally, I took the time to chew one, to savor the taste. It was good! It tasted much like human flesh, only spicier and less rancid. I could get used to this, I thought.