[GIS] OpenLayers2 change feature’s style

developmentopenlayers-2web-mapping

Working with OpenLayers 2.11, I'm desperately trying to change my feature style as the user selects it (fairly simple I agree!).

Indeed, It seems easy but I can't see where It fails, perhaps someone experienced with OpenLayers could enlighten me.

Below is my code :

   function onFeatureSelect(event) 
   {

    var feature = event.feature;

    var styleWaypointSelect = new OpenLayers.StyleMap(
    {
        externalGraphic: 'img/map_marker.png',
        graphicWidth: 16, graphicHeight: 26, graphicYOffset: -24,
        title: 'selectedFeature'
    })


    var clonedFeature = waypointLayer.getFeatureById(feature.id);
    clonedFeature.style = styleWaypointSelect;

    waypointLayer.drawFeature(clonedFeature,styleWaypointSelect);
    waypointLayer.redraw(); /* refresh() I tried several things to refresh the layer but it doesn't seem to change anything at all*/

EDIT :

I finally figured out that OpenLayers StyleMap class allows different properties, "default", "delete", "temporary", "select".
(you can see this when you debug the style object in firebug)

I added the "select" style of my vector layer like this :

        var styleWaypoint = new OpenLayers.StyleMap({
              "default": new OpenLayers.Style({
                externalGraphic: 'img/mobile_loc.png',
                graphicWidth: 16, graphicHeight: 26, graphicYOffset: -24,
                title: 'marker'
            }),
               "select": new OpenLayers.Style({
                externalGraphic: 'img/mobile_loc_select.png',
                graphicWidth: 16, graphicHeight: 26, graphicYOffset: -24,
                title: 'marker_select'
            })
        });

Best Answer

I know the topic is ab bit outdated, but just in case someone runs into this problem again you can use the following code to set the default and select style for an entire layer.

You can use other "well known redering intends" as described here.

style = new OpenLayers.StyleMap({
    "default": new OpenLayers.Style({
        strokeColor: "#339933",
        strokeOpacity: 1,
        strokeWidth: 3,
        pointRadius: 6,
    }),
    "select": new OpenLayers.Style({
        strokeColor: "#ffffff",
        strokeOpacity: 1,
        strokeWidth: 3,
        pointRadius: 6,
    })
});
pointLayer = new OpenLayers.Layer.Vector("Point Layer", {styleMap: style});