openlayersgeojson

Geojson Style Openlayers


Following the criterion of styling a geojson by applying filters, I have made this function. It doesn't give an error but it doesn't show the points with the different styles either.

//Style 1
var style = new Style({
    stroke: new Stroke({color: '#000000', width: 1}),
    fill: new Fill()
});

var puntStyle = function(feature){
    var value = feature.get('group');
    var color = value.includes('GARDEN') ? '#ffffff' :
                value.includes('HOUSE') ? '#ff7f7f' :
                value.includes('CHAPEL') ? '#ff0000' :
                value.includes('TOMB') ? '#7F0000' : '#3F0000';
    style.getFill().setColor(color);
    return style;
};

I use "value.includes" because the GeoJSON has values of the type: Garden 1, Garden 2... House 1, House 2... etc.

The option that works for me is defining different styles and checking if the value exists and assigning the style to it. But this way involves using more lines of code. I wanted to simplify it a little. I actually define 10 different styles.

// Style 2
const oneStyle = new Style({
    image: new CircleStyle({
        fill: new Fill({
            color: '#fff5f0'
        }),
        stroke: new Stroke({
            color: '#3B240B',
            width: 1.8
        }),
        radius: 6,
    })
});

// ... following styles ...

const puntStyle = function(feature) {
    var value = feature.get('group');
    if(value.includes('GARDEN')){
        return oneStyle;
    }else if(value.includes('HOUSE')){
        return twoStyle;
    }else if(value.includes('CHAPEL')){
        return threeStyle;
    }else if(value.includes('TOMB')){
        return fourStyle;
    }else{
        return style;
    }
};

Solution

  • Method 1 does not work for Points because they must be styled with an image property

    //Style 1
    var style = new Style({
        image: new CircleStyle({
            stroke: new Stroke({color: '#000000', width: 1}),
            fill: new Fill(),
            radius: 6,
        }),
    });
    
    var puntStyle = function(feature){
        var value = feature.get('group');
        var color = value.includes('GARDEN') ? '#ffffff' :
                    value.includes('HOUSE') ? '#ff7f7f' :
                    value.includes('CHAPEL') ? '#ff0000' :
                    value.includes('TOMB') ? '#7F0000' : '#3F0000';
        var fill = style.getImage().getFill();
        fill.setColor(color);
        style.getImage().setFill(fill);
        return style;
    }
    

    ;