Calculating the Distance between Zip Codes Using the Google Maps API – Part 1
A request came in recently to develop a feature for getting a list of organizations near a zip code provided by the user. They're looking for something very similar to a jobs website where you can narrow the search results to show only the ones within a 50 or 100 mile radius. The Google Maps API and Google's Distance Matrix service seem like great solutions for the problem.
Connecting to the Google Maps API
Before using Google's Distance Matrix, we need to tap into the Google Maps API. One way is to utilize the code from Asynchronously Loading the API. Note: you'll need to obtain an API key which is freely available. Your API key should replace the "YOUR_API_KEY" value below.
//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
The onload event prevents the map from loading until the rest of the page loads first. Once done, the callback function (initialize) is executed. This is where we'll build the Google Map, utilize the Distance Matrix service, etc.
Adding a Map
We're not technically supposed to use the Distance Matrix service without displaying a Google Map, so let's do so now. Google's sample code says to add a <div>Â tag to the <body> portion of the page. For the sake of this example, we'll add two <div> tags—one for the output and another for the map.
<div id="zip_code_output"></div>
<div id="map_canvas" style="width:650px; height:600px;"></div>
The following JavaScript code will transform the plain <div>Â tag into a fully-featured Google Map:
//FUNCTION TO INITIALIZE THE GOOGLE MAP
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
//...
}
Feel free to customize the map as you see fit. At some point I may write about placing markers and other content, but that's beyond the scope of this post. Until then, everything you need can be found in the Google Maps API documentation.
Using the Distance Matrix
The Distance Matrix service needs an array of zip codes for the origin and destination points. We'll also indicate that the results should be calculated based on driving from one location to another and that the distance should be formatted as miles.
function initialize() {
//...
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//INITIALIZE GLOBAL VARIABLES
var zipCodesToLookup = new Array('05001', '10002', '10457');
var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
//EXECUTE THE DISTANCE MATRIX QUERY
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: zipCodesToLookup,
destinations: zipCodesToLookup,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function(response, status) {
//...response processed here...//
});
}
Again, a callback function is used to catch the API's response. We'll use an inline function this time. If the query was successful, loop through the results and add them to the output variable. Then display the output.
}, function(response, status) {
if(status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for(var i=0; i < origins.length; i++) {
var results = response.rows[i].elements;
for(var j=0; j < results.length; j++) {
output += '<tr><td>' + origins[i] + '</td><td>' + destinations[j] + '</td><td>' + results[j].distance.text + '</td></tr>';
}
}
document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
}
});
}
Final Code
Here's the stripped-down version of the code to show all the pieces put together. Note: you'll need to replace "YOUR_API_KEY" with the API key you obtained earlier.
<html>
<head>
<title>Distance Matrix Example</title>
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//INITIALIZE GLOBAL VARIABLES
var zipCodesToLookup = new Array('05001', '10002', '10457');
var output = '<tr><th scope="col">From</th><th scope="col">To</th><th scope="col">Miles</th></tr>';
//EXECUTE THE DISTANCE MATRIX QUERY
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: zipCodesToLookup,
destinations: zipCodesToLookup,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL
}, function(response, status) {
if(status == google.maps.DistanceMatrixStatus.OK) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for(var i=0; i < origins.length; i++) {
var results = response.rows[i].elements;
for(var j=0; j < results.length; j++) {
output += '<tr><td>' + origins[i] + '</td><td>' + destinations[j] + '</td><td>' + results[j].distance.text + '</td></tr>';
}
}
document.getElementById('zip_code_output').innerHTML = '<table cellpadding="5">' + output + '</table>';
}
});
}
//FUNCTION TO LOAD THE GOOGLE MAPS API
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="zip_code_output"></div>
<div id="map_canvas" style="width:650px; height:600px;"></div>
</body>
</html>
Example Output
The following is the output from the completed code. Note that I stylized the table slightly to match the formatting of the blog.
From | To | Miles |
---|---|---|
WHITE RIV JCT, VT 05001, USA | WHITE RIV JCT, VT 05001, USA | 1 ft |
WHITE RIV JCT, VT 05001, USA | KNICKERBOCKER, NY 10002, USA | 272 mi |
WHITE RIV JCT, VT 05001, USA | Bronx, NY 10457, USA | 261 mi |
KNICKERBOCKER, NY 10002, USA | WHITE RIV JCT, VT 05001, USA | 266 mi |
KNICKERBOCKER, NY 10002, USA | KNICKERBOCKER, NY 10002, USA | 1 ft |
KNICKERBOCKER, NY 10002, USA | Bronx, NY 10457, USA | 13.4 mi |
Bronx, NY 10457, USA | WHITE RIV JCT, VT 05001, USA | 258 mi |
Bronx, NY 10457, USA | KNICKERBOCKER, NY 10002, USA | 13.1 mi |
Bronx, NY 10457, USA | Bronx, NY 10457, USA | 1 ft |
Conclusion
The Distance Matrix service is relatively straight forward. After providing a list of origin and destination points, we're given the distance between each of those points. However, the requests are limited to 25 origins and 25 destinations per query. If you need more, stick around for next week's post.
Related Posts
- Calculate Distance Between Zip Codes Part 2: Build the Search Engine
- Calculate Distance Between Zip Codes Part 1: Geocode Database Entries with the Google Maps API
- End PHP Scripts Gracefully After a Failed Database Connection
- Calculating the Distance between Zip Codes Using the Google Maps API – Part 2
0 Comments
There are currently no comments.
Leave a Comment