Monday, December 12, 2011

Add your own property field to Google Maps polygons

The Google Maps Overlay classes such as the Polygon or Polyline classes have only standard properties including clickable, fillColor, paths, zIndex, etc. In certain circumstances, it is advantageous to extend the overlay classes to include additional user-defined properties such as the polygon title or road name so that the user-defined values can be retrieved when certain events occur - such as a polygon click event.

It is quite simple to extend the class to include your own properties as shown in the example code listing below. Simply add in the property and value when the overlay class is created.

The example code listing below shows how to extend a polygon to include a new property field named html It also illustrate how to retrieve the property value back when the polygon is clicked.


 //...etc...  
 var contentString = "Hello world, this is my new attribute";  
 //Create a new polygon with an additional user defined property: html  
 var leftBot = new google.maps.LatLng(0,0);  
 var leftTop = new google.maps.LatLng(2,0));  
 var rightTop = new google.maps.LatLng(2,2);  
 var rightBot = new google.maps.LatLng(0,2);  
 var polyCoords = [leftBot,     leftTop, rightTop,     rightBot, leftBot];                           
 var poly = new google.maps.Polygon({  
      html: contentString,  
      paths: polyCoords,  
      strokeColor: "#FF0000",  
      strokeOpacity: 0.8,  
      strokeWeight: 2,  
      fillColor: "#FF0000",  
      fillOpacity: 0  
 });                 
 poly.setMap(map);  
 //Add an on polygon click event handler to display the user defined property when clicked  
 google.maps.event.addListener(poly, "click",   
      function (evt){  
           var contentString = this.html;  
           var vertices = this.getPath();  
           var xy = vertices.getAt(0);  
           _infoWnd.setContent(contentString);  
           _infoWnd.setPosition(evt.latLng);  
           _infoWnd.open(map);  
      }  
 );       
 //.... etc....  

1 comment:

Unknown said...

sos groso sabelo!, +1 y a favoritos