Google Maps and Distance Calculating

John | .Net | Wednesday, October 3rd, 2007

At the marketing agency I work for we have just recently finished a medium sized project which required the use of Postcode distance calculating. We looked at several solutions including PostCodeAnywhere, which I have used in the past for other projects, but our concern was the cost of the postcode data. Even obtaining the data directly from the Royal Mail was very expensive. Costs looked likely to be around £2,000 for a setup fee and then ongoing yearly costs of around £500. As the project wasn’t a guaranteed success for the client we wanted to keep the costs down for them.

At the same time of working on this project another team member was using the Google Maps API for putting locations on a map for a different client. As a team we wondered whether we could use the same technology to calculate distances between postcodes, however my concern was that I didn’t want a JavaScript solution as this would mean some of the visitors to the site wouldn’t be able to the search tool effectively. Fortunately Google do also provide some data through an XML service.

http://maps.google.com/maps/geo?q=PostCodeHere&output=xml&key=APIKeyHere

Bingo, that was exactly what we needed. The only limitation was that the maximum number of requests we could make a day were 50,000 but we figured this wouldn’t be an issue. So now we have the capability to get the Latitude and Longitude values for every postcode, so with some simple trigonometry it was possible to calculate the distance as the crow flies. At first the client was worried that this would mean the distances weren’t particularly accurate, but we managed to explain to them that all distance calculators, except for route planners, provided the distance as the crow flies.

The function for calculating the distance can be seen below.
private double CalculateDistance(Coordinates Start, Coordinates End )
{
double distance = 0;
double Lat1 = Start.Latitude;
double Lon1 = Start.Longitude;
double Lat2 = End.Latitude;
double Lon2 = End.Longitude;

// Calculate distance between point (includes taking into account curveture of Earth)
double theta = Lon1 - Lon2;
double dist = Math.Sin(deg2rad(Lat1)) * Math.Sin(deg2rad(Lat2)) + Math.Cos(deg2rad(Lat1)) * Math.Cos(deg2rad(Lat2)) * Math.Cos(deg2rad(theta));
dist = Math.Acos(dist);
dist = rad2deg(dist);
distance = dist * 60 * 1.1515;

return distance;
}

To limit the number of requested we made to Google we decided to store each Postcode with its latitude and longitude in a database table with a timestamp. Once the timestamp is over 6 months old we update the coordinate values.

So a big thanks to Google who have helped us provided a very cost effective solution to not only this client but future clients as well.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress | Theme by Roy Tanck