4
votes

I would have an openlayers vector layer with features scattered all over the map. I want to be able to click on a feature and have a message display.

I'm not sure if there is a way to add a listener/handler to each feature.

Any ideas?

3

3 Answers

8
votes

Add SelectFeture control:

var selectFeature = new OpenLayers.Control.SelectFeature(vector_layer);
map.addControl(selectFeature);
selectFeature.activate();

After that you can listen to select/unselect events on vector layer:

vector_layer.events.on({
  'featureselected': function(feature) {
       //display your message here
  },
  'featureunselected': function(feature) {
       //hide message
  }
});
5
votes

You need to use a combination of the SelectFeature control and one of the OpenLayers.Popup classes such as OpenLayers.Popup.FramedCloud. Here is an example of just that:

http://openlayers.org/dev/examples/select-feature-openpopup.html

In that example, try using the "draw polygon" option to draw a polygon (double-click on the map to complete the polygon). Then use "select polygon on click" and click on the polygon, and you will get a framed cloud popup.

You can view the source for the page to see how it this is done. Here are the relevant parts of the code. You can, of course, change the message to whatever you want to display in the framed cloud:

    var map = <your OpenLayers.Map object>;
    var polygonLayer = <your vector layer>;

    selectControl = new OpenLayers.Control.SelectFeature(polygonLayer,
            {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
    map.addControl(selectControl); // not in the example, but do this

    function onPopupClose(evt) {
        selectControl.unselect(selectedFeature);
    }

    function onFeatureSelect(feature) {
        var message = "<div style='font-size:.8em'>Feature: " + feature.id +"<br>Area: " + feature.geometry.getArea()+"</div>";

        selectedFeature = feature;
        popup = new OpenLayers.Popup.FramedCloud("chicken", 
            feature.geometry.getBounds().getCenterLonLat(),
            null,
            message,
            null, true, onPopupClose);
        feature.popup = popup;
        map.addPopup(popup);
    }

    function onFeatureUnselect(feature) {
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }

Here are the references for the controls you will be using:

0
votes

If there are many vector layers is it necessary to write "layer_name.events.on ..." for each layer? Is it possible to make a list of layers and assign ".events.on" to all of them?