http://www.developer.com/

Back to article

Creating Custom Overlays with the Google Maps API


March 12, 2010

No matter how complex a Google Maps API implementation is, the application usually is focused on specific locations such as addresses or routes, for instance, the shortest path between two towns. But what if you want to represent spatial data in terms of a larger area, such as the blast radius of a nuclear explosion or the incidence of flu outbreak within major cities (see Figure 1)?


Figure 1. Circular Overlays in Google Maps API:
Here is a circular overlay atop major Ohio cities.

You can accomplish such spatial data representations using a Google Maps API feature known as the custom overlay, a technique I explain in this tutorial.

Creating a Custom Overlay

If you've ever added a marker or charted a route using the Google Maps API, you actually created a custom overlay. An overlay is any foreign object that is situated atop a rendered map. It could be a marker, a shape such as a circle, an image, or even another map or map inset.

AS an example, suppose you wanted to place a 15-mile radius around the center of Columbus, Ohio. Because the API does not offer a way to explicitly add specific objects such as a circle or square to a map, you instead need to calculate all of the points that together comprise the object's outline. Performing such a task requires a bit of a math refresher, as it involves several calculations for determining the points on a circle given a radius and center. This formula is available and discussed in detail on countless web sites, so I'll forego the mathematical explanation and instead show you the JavaScript function used to create the circle:

function drawCircle(lat, lng, radius, stroke, sColor) {
 
  // Degrees to radians 
  var d2r = Math.PI / 180;
  // Radians to degrees
 var r2d = 180 / Math.PI;
  // Earth radius is 3,963 miles
 var cLat = (radius / 3963) * r2d;
  var cLng = cLat / Math.cos(lat * d2r);
 
  // Store points in array 
  var points = [];
 
  // Calculate the points
  // Work around 360 points on circle
  for (var i=0; i < 360; i++) {
 
    var theta = Math.PI * (i/16);
 
    // Calculate next X point 
    circleX = lng + (cLng * Math.cos(theta));            
    // Calculate next Y point 
    circleY = lat + (cLat * Math.sin(theta));
    // Add point to array 
    points.push(new GPoint(circleX, circleY));
 
  };
 
  // Add points to map 
  map.addOverlay(new GPolyline(points, sColor, stroke));
 
}


Therefore, to create a circle around a specific point, you need to pass five parameters to the drawCircle() function:

  • lat: The latitudinal component of the circle's center
  • lng: The longitudinal component of the circle's center
  • radius: The circle's radius
  • stroke: The circle's stroke weight, defined in pixels
  • sColor: The circle's stroke color, defined using hexadecimal format

The API's role in this action is really confined to a single call to the following line:

map.addOverlay(new GPolyline(points, sColor, stroke)); // Add points to map


As you can see, the GPolyline() class instantiator accepts three parameters: the points array, the stroke color, and the stroke width. This object is subsequently passed to map.addOverlay(), the map object having been defined per usual at some previous point in the script. With the drawCircle() function defined, all you need to do is call it, passing along the required parameters.

As an example, the following three calls respectively will plot circles having a radius of 20 miles over Cincinnati, Cleveland, and Columbus, Ohio.

// Cincinnati
drawCircle(39.144972, -84.476623, 20, 5, '#000000');
 
// Cleveland
drawCircle(41.498806, -81.707382, 20, 5, '#000000');
 
// Columbus
drawCircle(39.954578, -82.998689, 20, 5, '#000000');


Adding Some Color

While using the GPolyline() function enables you to bring special attention to specific areas on a map, sometimes you'll want to add some extra color to not only raise the profile of a particular area but also perhaps to lend some context to the various locations. For example, suppose you wanted to create a map that depicts the incidence of zombie outbreaks according to a color-coded legend (see Figure 2). To accomplish this, you should use the GPolygon class, which allows you to define both an overlay fill color and opacity.


Figure 2. Color-coded Overlays with the Google Maps API:
You can use color-coded overlays to depict zombie outbreak incidences.

You can achieve this effect by using the previously defined drawCircle() function. Simply swap out the GPolyline() call with the following:

map.addOverlay(new GPolygon(points, sColor, stroke, .50, sColor, .50));


To cut corners, I've reused the sColor value twice. However, as hopefully the parameter pattern indicates, you can control both the shape fill and line independently of one another.

Creating Irregularly Shaped Overlays

Of course, circles are just one of innumerable shapes you can create using the Google Maps API. For instance, you can create a triangle-shaped overlay that bounds three cities simply by identifying a set of four coordinates and then passing that set to the GPolyline class, as demonstrated here:

var polyline = new GPolyline([
  new GLatLng(39.144972, -84.476623),
  new GLatLng(41.498806, -81.707382),
  new GLatLng(39.766325, -86.187744),
  new GLatLng(39.144972, -84.476623)
], "#000000", 3);
map.addOverlay(polyline);


Executing this code creates the map depicted in Figure 3.


Figure 3. Bounding the Area Between Cities:
You can create a triangle-shaped overlay that bounds three major cities.

Conclusion

My occasional Google Maps API series has covered quite a bit of ground during the past five years, introducing topics ranging from plotting markers to more advanced features such as calculating road distances and trip duration between two points.

The Google Maps API's powerful overlay capabilities, however, go far beyond the simple addition of markers and routes that I've discussed in the past. You can create any conceivable shape, offering new ways to visually describe your spatial data. If you do anything interesting with what you've learned in this tutorial, I'd love to hear about it!

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com. He is the author of several popular books, including "Easy PHP Websites with the Zend Framework," "Easy PayPal with PHP," and ""Beginning PHP and MySQL, Third Edition."

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date