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:

If this post has helped you out, feel free to consider throwing a small donation my way.