GPolygon Example

Wednesday, January 24, 2007 at 10:11:00 AM



Hi all, my name's Pamela Fox. I've just joined the Maps API team and will be working part-time on various projects until I finish my Masters in C.S. at USC and join full-time. I'm looking forward to making GMaps easier to work with for developers and first-timers.

To start off my time here, I've made a simple example showing off what you can do with the recently documented GPolygon. Even if you're not the type of person who enjoys a good square, pentagon, or googolgon, you can also use this class to generate stars and "circles" with only slight changes in code. The example below lets you click on the map to generate either squares, circles, or polygons of random color, size, and sides (for polygons/stars). Play around with it - Trust me, it's fun!

Here's how it works:

  • We define several utility functions to aid in generating random numbers and colors
  • When the map is clicked, we find the clicked pixel using fromLatLngToPixel on the result of G_NORMAL_MAP.getProjection().
  • We start generating random variables for small radius, large radius (used for stars), number of sides, and color.
  • If the draw mode selected is polygon, we iterate from 0 to number of sides. In each iteration, we calculate the new pixel location using good old trigonometry. We convert the pixel back to latitude/longitude using fromPixelToLatLng and add it to our points array.
  • If the draw mode selected is a star or circle, the process is almost the same. For stars, we iterate twice as much as the number of sides, calculating points at the large radius on the odd iterations. For circles, we ignore the randomly generated number of sides and always iterate 20 times around the clicked pixel for a nice round look.
  • Now for the magic - we create a new GPolygon with the points array and style parameters, and add it to the map.
  • Now here's the challenge: my own example is pretty useless, except for its teaching value. How can you put GPolygon to work for your app? Exploit the GPolygon for all it's worth (and don't forget its friend, GPolyline), and ping us with your creations on the forums.