Dec 082012
 
Article Javascript

In a previous post of the series on Google maps we have seen how to add markers to the map to annotate specific points in it.

Sometimes, we would like to highlight an area on the map, rather than a single point. Using the Google Maps API it is also possible to highlight an area on the map defined by means of a single polygon or a set or polygons.

Finally, if we want to highlight a path, it is also possible to do it by means of a polyline.

In this post we will explain how to highlight areas and paths on the map with Google Maps API V3, with usage examples.

Polygons

To define an area we start by creating a polygon as a javascript array of elements of type google.maps.LatLng. In the example below a triangle covering the Bermuda Triangle is created:

Next, an instance object of class google.maps.Polygon is created. The array of points is assigned to the “paths” attribute, and other properties to render the area are specified as well, such as the line and background color and opacity, the line with, etc:

Finally, the area is displayed on the map with a call to the “setMap()” method:

Areas with more than one polygon

The region to be highlighted may be more complex than what can be represented with a single polygon:

– If there are two or more disjoint areas in it

– If there are “holes” inside the area that do not belong to the region to be highlighted.

In the first case, an array of polygons is assigned to the “paths” attribute of the Polygon object

The sample data above adds two disjoint triangles to the map:

 

To create a hole inside a polygon, another polygon representing the hole is added to the array, after the container polygon. Besides, if the points of the containing polygon are in “clockwise” order, the points of the hole must be in counterclockwise order, and viceversa.

Example:

The polygon array above creates a triangular hole inside the container triangle:

 

Polylines

A polyline is created in the same way as a polygon, as an array of elements of type google.maps.LatLng. Then, an instance object of class google.maps.Polyline is created.. The array of points is assigned to the “path” attribute, and also the with, color and opacity of the line to be drawn are assigned as attributes of the Polyline object:

The code above draws on the map a line representing a flight plan from USA to Australia:

References:

Related posts:

 Posted by at 9:28 am

 Leave a Reply

(required)

(required)