April 17, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

On the Road with the Google Maps API

  • June 15, 2009
  • By W. Jason Gilmore
  • Send Email »
  • More Articles »

In the previous installment of this occasional series discussing the Google Maps API, we used the API and a PHP library named GoogleMapAPI to plot and calculate a route along a map. Uses for such a feature are many, among them determining distance as the crow flies between two points, and even a quick gauge for figuring the length of a simple jogging or bicycling route. However, although useful, the limitations of such a feature quickly become apparent when the need arises to calculate the distance of a more complex route. Or what if you needed to chart a much longer route, such as one which would take the user from Columbus, Ohio to Cleveland, Ohio? For instance, charting the route as accurately as shown in Figure 1 would likely prove fairly tedious using this approach.

Figure 1. Charting a complex route

Thankfully, the Google Maps API offers a feature which can greatly reduce the work involved in creating complex routes such as this. In fact, you'll be able to use this feature to create a complex multi-point route simply by clicking on your starting and concluding points, letting the API plot what it deems to be the most direct route. Sounds cool, doesn't it? In this tutorial I'll show you how to implement this feature into your website, and perform other tasks such as determining the distance of the route, and even displaying route directions such as those available at http://maps.google.com/.

Snapping Points to a Route

The first thing we'll need to figure out is how the API will plot a route along the known roads and other byways. This is accomplished using the loadFromWaypoints() method, which will accept an array of up to 25 coordinates (or alternatively addresses, and even a mix of the two), and then work out the route which connects these points. The following function will add a marker to the map, and append the marker's coordinates to an array named coordinates (defined in the typical initialize() function). If the coordinates array ever consists of more than one set of coordinates, the loadFromWaypoints() method is called, resulting in a route between the coordinates being drawn.

function plotRoute(overlay, latlng) {
  // Create a new marker based on the coordinates
  var marker = new GMarker(latlng);
  
  // Instantiate the GDirections class
  var directions = new GDirections(map);
  
  // Add the new marker to the map
  map.addOverlay(marker);
 
  // Create the new array element
  coordinates_array_element = latlng.lat() + "," + latlng.lng();
 
  // Add the new array element to the map
  coordinates.push(coordinates_array_element);
 
  // If > one point on the map, plot the route between these two points
  if (coordinates.length > 1) {
 directions.loadFromWaypoints(coordinates);
  }
}

As was demonstrated in the previous article, to execute a function when the user clicks on a map, just attach a listener to the map, as is shown below. I've placed this call in the initialize() function. If you don't know what purpose the initialize() function serves, be sure to consult earlier articles in this series.

GEvent.addListener(map, "click", plotRoute);

Avoiding Highways

The route plotted between Columbus and Cleveland logically guided the user along one of the state's major highways, namely I-71. But what if you were planning a marathon bicycle ride between Columbus and Cleveland? You can tell the API to avoid using highways by modifying the loadFromWaypoints() method call like so:

directions.loadFromWaypoints(coordinates, {"avoidHighways": true});

Once in place, reload the map and again plot the points between Columbus and Cleveland. You'll notice the outbound route from Columbus avoids using I-71, as shown in Figure 2.

Figure 2. Avoiding highways along the route

You can pass along other properties as well, including one (locale)for changing the map locale, and another (preserveViewport) which will zoom the map to an appropriate level in order to ensure the entire route appears within the map viewport. Consult the API documentation for a complete list of available properties.

Calculating the Route Distance and Trip Duration

You can also easily determine the distance and estimated travel time using the GDirection class' getDistance() and getDuration()methods, respectively. However, because these values are not returned until the loadFromWaypoints() method returns the route, you'll need to use a listener to retrieve the values at the appropriate time. For instance, the following listener waits for the directions object to load. Once loaded, the duration is retrieved, converted into minutes, and updated within a div named duration placed somewhere within the web page.

GEvent.addListener(directions, "load", function() {
  var duration = (directions.getDuration().seconds / 60).toFixed(2);
  document.getElementById("duration").innerHTML = duration + 
  " minutes to arrive at your destination.";
});

Figure 3. Displaying the estimated travel time

Displaying Route Directions

Sometimes you might wish to provide the user with directions from one point to the next. Adding this feature is shockingly easy; just modify your call to the GDirections object to identify the div where the directions should be inserted, like so:

var directions = new GDirections(map, document.getElementById("sidebar"));

After adding the sidebar div to your web page, you'll be able to create interfaces such as that shown in Figure 4.

Figure 4. Including travel directions

Conclusion

This and the previous article present you with two easy ways to determine distance between multiple points on a map, whether its as the crow flies or as somebody might travel along an established roadway. If you wind up doing anything interesting with these features, I'd love to hear about it!

About the Author

Jason Gilmore is founder of W.J. Gilmore, LLC, a publishing and consulting firm based out of Columbus, Ohio. His latest project is EasyPHPWebsites.com, a one-stop shop for learning the PHP language. Jason is the author of several books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is cofounder of CodeMash, a nonprofit organization tasked with hosting an annual namesake developers conference.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel