1
votes

I'm a bit of an OpenLayers newbie and I'm using v3.0.0.

I've recently added a style function code to my map to show labels on features, using some code I found online:

function labelStyle(feature, resolution) {
    var text = '';

    if (options.showLabels && (resolution < 80)) {
        text = feature.get('name');
    }

    if (!styleCache[text]) {
        styleCache[text] = [
            new window.ol.style.Style({
                stroke: new window.ol.style.Stroke({ color: [0, 153, 255, 1], width: 2.5 }),
                fill: new window.ol.style.Fill({ color: [0, 255, 0, 0.1] }),
                text: new window.ol.style.Text({
                    font: '16px Calibri,sans-serif',
                    text: text,
                    fill: new ol.style.Fill({
                        color: [255, 255, 255, 1]
                    }),
                    stroke: new ol.style.Stroke({
                        color: [0, 0, 0, 1],
                        width: 3
                    })
                })
            })
        ];
    }

    return styleCache[text];
}

This works fine, I can pass this function instead of a style when creating the vector layer and labels now appear in the centre of the features. However, if I select a feature, the label disappears.

So my aim is to be able to apply this style to selected features.

I've seen the code for a StyleMap, where you can define styles for default, select, etc. But if I implement this StyleMap, I lose the ability to get the name from the feature to use for labelling.

It seems I can have one but not the other.

1
Why OpenLayers 3.0.0? Latest release is 3.10.1, with many feature and bug fixes done since 3.0. - Alvin Lindstam
Personally I like to keep up to date. I was looking at upgrading this morning, as far as I can tell there are only 2 breaking changes in our code, so I might upgrade later this week if I can convince the team. - Adrian Thompson Phillips
Yes, most things have improved since 3.0. If nothing else, the documentation is more complete. I noticed that the style option I suggested in my answer was undocumented in the 3.0.0 docs. - Alvin Lindstam

1 Answers

4
votes

ol.interaction.Select removes selected features from their original layer, and adds them to a separate layer/FeatureOverlay. So any styles used for a layer does not apply to features selected (away) from it.

ol.interaction.Select accepts a style option, just like ol.layer.Vector, which applies to the selected features. Include your style function in the interaction options, and you should be good to go.