NoRyb
NoRyb

Reputation: 1544

OpenLayers3 - Style each Feature individually

I am adding features to a map by reading their WKT-String:

var feature = wkt.readFeature(entity.WellKnownText);
feature.bxObject = entity;
src.addFeature(feature);

Each feature has a bxObject-Property, and this Property contains the "radius"-Property.

I style the layer, to which the features are added like so:

var layer = new ol.layer.Vector({
    source: src,
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 6,
            stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1
            }),
            fill: new ol.style.Fill({ color: [0, 0, 255, 0.1] })
        })
    })
});

I want the radius-Property of the style to be dynamic. What I did and works as a workaround is the following:

var layer = new ol.layer.Vector({
    source: src,
    style: function (feature, resolution) {
        return [
            new ol.style.Style({
                image: new ol.style.Circle({
                    radius: feature.bxObject.radius || 6,
                    stroke: new ol.style.Stroke({
                        color: 'blue',
                        width: 1
                    }),
                    fill: new ol.style.Fill({ color: [0, 0, 255, 0.1] })
                })
            })
        ];
    }
});

But this creates a new style for each feature... I potentially draw 100s of features and I even have the subjective opinion, that it slows everything down. Is this really the way it is done?

I found this stackoverflow post. But I had no luck trying to interpolate with "${...}". I guess this is an openLayers 2 feature:

var layer = new ol.layer.Vector({
    source: src,
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: "${bxObject.radius}",
            stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1
            }),
            fill: new ol.style.Fill({ color: [0, 0, 255, 0.1] })
        })
    })
});

Upvotes: 2

Views: 1249

Answers (1)

bartvde
bartvde

Reputation: 2126

Yes this is really the way, but you should keep a style cache and re-use when possible. See for instance: http://openlayers.org/en/v3.10.1/examples/kml-earthquakes.html

Upvotes: 1

Related Questions