1

I'm trying to draw a new layer every time user clicks on the map. My styling function can be seen below;

function CatchmentLayerStyleFunction(feature) {
    var colors = ['rgba(255,0,0,0.5)', 'rgba(0,255,0,0.5)',
        'rgba(0,0,255,0.5)', 'rgba(36, 201, 149,0.5)',
        'rgba(207, 242, 9,0.5)', 'rgba(241, 137, 9,0.5)',
        'rgba(8, 240, 240,0.5)', 'rgba(237, 118, 231,0.5)',
        'rgba(237, 26, 82, 0.5)', 'rgba(237, 26, 222)'];
    var color = new Style({
        stroke: new Stroke({
            color: colors[Math.floor(Math.random() * colors.length)],
            lineDash: [4],
            width: 3
        }),
        fill: new Fill({
            color: colors[Math.floor(Math.random() * colors.length)]
        })
    });

    return color
};

As you can see I'm randomly coloring the polygons. My function that adds the layers to map is like ;

var vectorSource = new VectorSource({
                renderMode: 'image',
                features: (new GeoJSON()).readFeatures(data[0], {
                    dataProjection: 'EPSG:4326',
                    featureProjection: 'EPSG:3857'
                })
            });
            map.addLayer(new VectorLayer({
                'title': 'Catchment',
                source: vectorSource,
                style: CatchmentLayerStyleFunction
            }));
            map.getView().fit(vectorSource.getExtent());
        });

But as you can see in the gif, everytime I pan or zoom on the map styles of these newly added polygons are changing. How can one fix styles for the layers ?

1 Answer 1

1

You would need to assign a color to the feature and, once set, continue to use that, for example:

function CatchmentLayerStyleFunction(feature) {
    var colors = ['rgba(255,0,0,0.5)', 'rgba(0,255,0,0.5)',
        'rgba(0,0,255,0.5)', 'rgba(36, 201, 149,0.5)',
        'rgba(207, 242, 9,0.5)', 'rgba(241, 137, 9,0.5)',
        'rgba(8, 240, 240,0.5)', 'rgba(237, 118, 231,0.5)',
        'rgba(237, 26, 82, 0.5)', 'rgba(237, 26, 222)'];
    var color = feature.get('color');
    if (!color) {
        color = new Style({
            stroke: new Stroke({
                color: colors[Math.floor(Math.random() * colors.length)],
                lineDash: [4],
                width: 3
            }),
            fill: new Fill({
                color: colors[Math.floor(Math.random() * colors.length)]
            })
        });
        feature.set('color', color);
    }
    return color;
};
1
  • Hi Mike, thanks for the response, I've changed the var declarations of the variables to const and it started to work properly.
    – Capan
    Commented Feb 20, 2019 at 14:11

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.