Search code examples
javascriptjquerycssopenlayersgeoserver

OpenLayers Vector Style change issue


When I click on button on map I would like to change vector style (fillColor). I tried this with no luck.

var map;
var layer, wms;

function init() {
    map = new OpenLayers.Map('map');
    wms = new OpenLayers.Layer.WMS(
        "OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {
        layers: 'basic'
    });
    var myStyle = {
        fill: true,
        fillColor: "#ff0000"
    };
    layer = new OpenLayers.Layer.Vector("WFS", {
        style: myStyle,
        strategies: [new OpenLayers.Strategy.BBOX()],
        protocol: new OpenLayers.Protocol.WFS({
            url: "http://demo.opengeo.org/geoserver/wfs",
            featureType: "tasmania_roads",
            featureNS: "http://www.openplans.org/topp"
        })
    });

    map.addLayers([wms, layer]);
    map.setCenter(new OpenLayers.LonLat(146.7, -41.8), 6);

        var panel_type2 = new OpenLayers.Control.Panel({
        displayClass: 'Panel2'
    });
    map.addControl(panel_type2);

    var redraw = new OpenLayers.Control.Button({
        displayClass: 'first',
        trigger: function () {
            layer.destroyFeatures();
            map.removeLayer(layer);
            var myStyle = {
                fill: true,
                fillColor: "#DFDFFF"
            };
            layer = new OpenLayers.Layer.Vector("WFS", {
                style: myStyle,
                strategies: [new OpenLayers.Strategy.BBOX()],
                protocol: new OpenLayers.Protocol.WFS({
                    url: "http://demo.opengeo.org/geoserver/wfs",
                    featureType: "tasmania_roads",
                    featureNS: "http://www.openplans.org/topp"
                })
            });

            map.addLayers([layer]);
        }
    });
    panel_type2.addControls([redraw]);
}

JSFIDDLE

When I click on button I am trying to redraw vector layer with new style. But its not working. Could someone brief me why its not changing fillcolor and How can I change?

Help Would be appreciated. :)


Solution

  • Your issue is that what is being returned from the wfs request is just lines, there are no polygons, so your fillStyle is being ignored, as there is nothing to apply it to. I have updated your fiddle and put a strokeColor attribute in your stylemap, and now it works as expected:

    var myStyle1 = {
          fill: true,
          fillColor: "#DFDFFF",
          strokeColor: "#FF0000"
    };
    

    Updated jsFiddle