I covered in my post in August of last year how to get the distance between two sets of co-ordinates using the Google Maps API. The only problem with using the Haversine formula is that the distance calculated is “as the crow flies”. If, for example, you were finding the closest branch of a particular store chain, the closest branch “as the crow flies” might actually be further than another branch when driving there — there could be one-ways systems, rivers, restricted height bridges, etc. that affect the distance when travelling to a branch.
This article will use another of Google Maps’ APIs — the Directions API — to calculate the distance between two places using whatever mode of transport you choose (by default, driving).
Posted on 16th August 2012
May 2013 Update: I’ve written a follow up post to this one, detailing how to find the distance between two locations using the Google Maps Directions API. I’ve also added the option to download the source code in full at the end of the post.
I wrote an article back in February on using the Google Maps API together with the W3C Geolocation API to show a user’s location on a map. The article was well received and I am going to build on the subject by going through how, with the help of Google Maps API once again, to find the distance between two locations; one of which could be found by using Geolocation as described in the previous article.
The method is actually quite simple; all we need to do is get the latitude and longitude co-ordinates of the two locations we want to find the distance between, and then using a mathematical formula, obtain the distance between them. These locations will depend on your application; they could be a user’s current location that is found using Geolocation, a town name, post/zipcode, or just a pre-determined set of co-ordinates – that part is up to you.