Take the 2-minute tour ×

I want to add a listener to a single polygon. Currently, I am trying to add one that makes a polygon opaque when you click on it, but I should be able to add any general listener. OpenLayers.Layer has an events property, but there is no such property for OpenLayers.Feature or OpenLayers.Geometry.Polygon.

This is my setup:

  • An OpenLayers.Layer.Vector layer, pLayer, called "polygon layer" that contains all of the polygons.
  • A function handleClick that sets this.style.fillOpacity = 1. this is supposed to refer to the polygon clicked on
  • For each polygon, I call:

    pLayer.events.register('click', polygon, handleClick);

The issue with this setup is that when I click on any of the polygons, it fires the event for all polygons on that layer and every polygon becomes opaque. How do I make it so that the event only fires for individual polygons?

I need this to be general. Basically, I want to be able to add any type of listener to a single polygon. My overall goal is to create an interface between Google Maps and OpenLayers, and I Google Maps you can add an event to a single polygon.

Will I need to put every polygon on a separate layer? If that is the case, how do I set up the renderer for each of those polygon layers? Or is there a way to keep all polygons in the same layer and have the event handle each of them individually?

share|improve this question

migrated from stackoverflow.com Jun 12 '12 at 14:51

This question came from our site for professional and enthusiast programmers.

1 Answer 1

up vote 2 down vote accepted

Use SelectFeature to handle the clicks for individual features.

Here's an example: http://openlayers.org/dev/examples/select-feature.html

share|improve this answer
Ok. I guess I'll need to get a little tricky about interfacing with the Google Maps API. That does seem like the best option for selecting polygons, though. –  dbmikus Jun 12 '12 at 16:08

Your Answer


