[GIS] Change Icon of Single Vector Feature in Layer

featureslayersopenlayers-2

Currently I am trying to change the icon of a particular feature of a vector layer that the user is focusing on. I add each feature to the map like so:

var point = new OpenLayers.Geometry.Point(pt.lon, pt.lat);
var markerStyle = OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'],  {
    externalGraphic: iconURL
});
var marker = new OpenLayers.Feature.Vector(point, attributes, markerStyle);

Later I do the following to update the feature's icon:

var marker = this.findSelectedMarker();
if (marker) {
    marker.style.externalGraphic = newIconUrl;
    this.layer.redraw();             
}

But when the layer redraws, all features in my layer use the newIconUrl, not simply the selected marker that I am trying to update.

How can I change the icon of the one selected feature of my layer? Thanks.

Best Answer

See my LIVE DEMO. Here is working code:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>Title</title> 
<script src="http://openlayers.org/dev/OpenLayers.js"></script>

<script type="text/javascript">
function init(){

    options = {
        div: "map",
        zoom: 2,
        center: [0, 0],
        layers: [
            new OpenLayers.Layer.OSM()
        ]
    };
    map = new OpenLayers.Map(options);
    vector = new OpenLayers.Layer.Vector();
    map.addLayer(vector);

    var point1 = new OpenLayers.Geometry.Point(0,0);
    var point2 = new OpenLayers.Geometry.Point(1000000, 1000000);

    marker1 = new OpenLayers.Feature.Vector(point1, null, {
        externalGraphic: "http://www.iconfinder.com/ajax/download/png/?id=73073&s=32",
        graphicWidth: 32,
        graphicHeight: 32,
        fillOpacity: 1
    });

    marker2 = new OpenLayers.Feature.Vector(point2, null, {
        externalGraphic: "http://www.iconfinder.com/ajax/download/png/?id=73066&s=48",
        graphicWidth: 32,
        graphicHeight: 32,
        fillOpacity: 1
    });

    vector.addFeatures([marker1, marker2])
}

function updateIcon(f) {
    f.style.externalGraphic = "http://www.iconfinder.com/ajax/download/png/?id=73070&s=32";
    vector.drawFeature(f)
}
</script> 
</head> 
<body onload="init()"> 
    <div id="map" style="width:640px; height:480px;"></div> 
    <input type='button' value='Update Icon' onClick="updateIcon(marker1)"/>
</body> 
</html>