Search code examples
javascriptshapefileopenlayers-6

How do I change a shape file feature styles before rendering?


The shape file content are:
bbox = array[4]
features = array[97]
|_feature[0] -> [97]
   |_geometry (polygon)
      |_coordinates = array[110] points

None of the polygons have any style assigned. The layer to which the feature vector is assigned has a default StyleFunction.

What I try to do is to set fill colors to each polygon and to disable the layer default style.

If I comment out the two lines under "Disable default style" all plygon gets the default style. Otherwise, no polygons are drawn at all. What should I do to make it work?

This is my code:

loadshp({
        url: filename,
        encoding: 'UTF-8',
        EPSG: 3857
    },
    function(data) {
        let features = new ol.format.GeoJSON().readFeatures(data, {
            featureProjection: 'EPSG:3857'
        });
        
        /* Assign style to each feature */
        for (let i = 0; i < features.length; i++) {
            let fill = new ol.style.Fill({
                color: 'rgba(100,255,255,0.8)'
            });
            let stroke = new ol.style.Stroke({
                color: '#3399CC',
                width: 1.25
            });
            features[i]['style_'] = new ol.style.Style({
                image: new ol.style.Circle({
                    radius: 5,
                    fill: fill,
                    stroke: stroke
                }),
                fill: fill,
                stroke: stroke,
            });
        }

        let layer = new ol.layer.Vector({
            source: new ol.source.Vector({
                features: features
            })
        });
        
        /* Disable default style */
        layer['styleFunction_'] = undefined;
        layer['style_'] = undefined;

         map = new ol.Map({
            layers: [new ol.layer.Tile({
                        source: new ol.source.OSM()
                    })],
            target: 'map',
            view: new ol.View({})
        });
        
        let source = layer.getSource();
        let extent = source.getExtent();
        map.getView().fit(extent, map.getSize());
                    
        map.addLayer(layer);
    }
);

Solution

  • The feature style must be set using setStyle() method

             features[i].setStyle(
                 new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: 5,
                        fill: fill,
                        stroke: stroke
                    }),
                    fill: fill,
                    stroke: stroke,
                })
            );
    

    This will automatically create a style function and override the layer default style.