Search code examples
openlayers

toggle fill Color in Openlayers style


I want to toggle fillColor of a point for a particular layer in Openlayers? Is it possible to do that? Something like blink?

fillColor:${getFillColor},
context : {
  getFillColor : function(feature) {
    if (feature.data.fillColor == 'red') {
      return 'yellow';
    } else {
      return 'red';
    }

which is not working


Solution

  • You should be able to accomplish that task without context-based styling even; you just need to periodically change the style of the vector layer and redraw it. Try something like:

    window.setInterval(function (){
        var defaultStyle = yourVectorLayer.styleMap.styles['default'].defaultStyle;
        yourVectorLayer.styleMap.styles['default'].defaultStyle = {
            fillColor: defaultStyle.fillColor === 'blue' ? 'green' : 'blue',
            pointRadius: 10
        }
        yourVectorLayer.redraw();
    }, 1000);
    

    A complete working example follows

    var map = new OpenLayers.Map('map', {
        maxResolution:'auto',
        layers: [
            new OpenLayers.Layer.WMS( 
                "OpenLayers WMS",
                "http://vmap0.tiles.osgeo.org/wms/vmap0",
                {layers: 'basic'}
            ),
            new OpenLayers.Layer.Vector('Points', {
                styleMap: new OpenLayers.StyleMap({
                    pointRadius: 10, 
                    fillColor: "blue"
                })
            })
        ],
        center: [0,0]
    });
    
    var features = [];
    for (var i=0; i<100; i++) {
        var x = Math.random() * 360 - 180,
            y = Math.random() * 180 - 90;
        features.push(
            new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Point(x, y)
            )
        );
    }
    
    map.layers[1].addFeatures(features);
    
    window.setInterval(function(){
        var defaultStyle = map.layers[1].styleMap.styles['default'].defaultStyle;
        map.layers[1].styleMap.styles['default'].defaultStyle = {
            fillColor: defaultStyle.fillColor === 'blue' ? 'green' : 'blue',
            pointRadius: 10
        }
        map.layers[1].redraw();
    }, 1000);