Search code examples
javascripteventsopenlayers

Click on GML track in OpenLayers


How can the click event on a GML track be caught in Open Layers?

I have the following code:

var gmlTrack = new OpenLayers.Layer.GML("Track", myGpxUrl, {
    format: OpenLayers.Format.GPX,
    projection: new OpenLayers.Projection("EPSG:4326")
});

I thought that the solution would be to add the following lines:

gmlTrack.events.register("click", gmlTrack, function(e){
    alert("Click on GPX track!");
});

But it doesn't work.

To be clear: I only want the click event to be triggered when the user clicks on the GPX track.

What am I doing wrong and how can I fix it?

Thank you.


Solution

  • You can achieve what you are looking for using a select feature control (which enables OpenLayers to know how to handle the events)

        selectControl = new OpenLayers.Control.SelectFeature(
            [gmlTrack],
            {
                clickout: true, toggle: false,
                multiple: false, hover: false,
                onSelect: trackSelected
            }
        );
    
        map.addControl(selectControl);
        selectControl.activate();
    

    And include some handler for trackSelected e.g.

    function trackSelected(feature){
        alert("something here");  
    }
    

    This is a useful OpenLayers example