1

Loading polygons from geoserver via OpenLayers using GeoJSON. My plan is to symbolize using attributes in the GeoJSON. I am struggling to access the attributes. Any insight appreciated:

The geometries are drawing, so I know that the GeoJSON is being passed from the backend to the client.

Wrapped in an init() function and called on page load:

        map = new OpenLayers.Map('map', options);

        var protocol = new OpenLayers.Protocol.WFS({ 
        url: "http://osgeostack:8080/geoserver/fjtests/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=fjtests:counties", 
        featureNS: "fj_tests", 
        featureType: "counties", 
        outputFormat: 'json', 
        readFormat: new OpenLayers.Format.GeoJSON() 
        }); 


        layer = new OpenLayers.Layer.Vector("GML", {
            isBaseLayer: true,
            //styleMap: new OpenLayers.StyleMap(style),
            protocol: protocol,
            strategies: [new OpenLayers.Strategy.Fixed()]
        });
            alert(layer.attributes) \\undefined
            alert(layer.features.length) \\ 0
            map.addLayer(layer)

1 Answer 1

1

You layer.attributes is undefined because attributes are on features (this means that among other things a features in a layer may have different attributes).

To style your map the simplest way would be to create a Style for your layer which contains OpenLayers Rules. Take a look at the OpenLayers Rule Based Style for a complete example, but I've written a simple one below that you could use for a polygon set (I'm assuming that's what "counties" will be). Note that the first argument of a Style is the default Symbolizer object.

var style = new OpenLayers.Style(
    {
        strokeColor: '#000000', //hex colour, in this case black
        strokeOpacity: 1,
        strokeWidth: 1,
        strokeLinecap: "butt", //or "round" or "square"
        fillColor: "#ffffff",
        fillOpacity: 0.3
    },
    // sample rule
    {
        rules: [
            new OpenLayers.Rule({
                filter: new OpenLayers.Filter.Comparison({
                    type: OpenLayers.Filter.Comparison.EQUAL_TO,
                    property: "name", // geojson property
                    value: "Unknown" //property value
                }),
                symbolizer: { //Colour Unknown counties red
                    strokeColor: '#ff0000',
                    strokeOpacity: 1,
                    strokeWidth: 1,
                    strokeLinecap: "butt",
                    fillColor: "#ff0000",
                    fillOpacity: 1,
                    label: "${name}" //Label based on name property
                }
            })
        ]
    }
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.