[GIS] OpenLayers: add a listener to a single polygon

eventsgoogle mapsmapsopenlayers-2

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?

Best Answer

Use SelectFeature to handle the clicks for individual features.

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