Reputation: 8756
I am trying to add features with different styling to a vector layer. I have a multiple lines which I want to have each one of them with different styling, but it looks like the styling I set for each feature were not affected. In other examples that I saw they had to have a unique layer to each styling.
Is there an option to add unique styling to each feature?
Upvotes: 1
Views: 5223
Reputation: 8756
OK, I found a way to do it and made a fiddle in case someone else want to do it:
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
style: 'Road',
source: new ol.source.MapQuest({layer: 'osm'})
})
],
view: new ol.View({
projection: 'EPSG:3857',
center: [-8908887.277395891, 5381918.072437216],
maxZoom: 19,
zoom: 2,
}),
});
var colorArr = ['blue','green','orange']
var featureCount = 100;
var features=[];
var feature, geometry;
var e = 25000000;
var points = [];
for (i = 0; i < featureCount; ++i) {
colorindex = Math.abs(parseInt((Math.random()*3).toFixed())-1);
if(i%10){
points.push([2 * e * Math.random() - e, 2 * e * Math.random() - e]);
continue;
}
feature = new ol.Feature({
geometry: new ol.geom.LineString(points, 'XY')
});
feature.setStyle(
new ol.style.Style({
fill: new ol.style.Fill({color: colorArr[colorindex],opacity: 0.7}),
stroke: new ol.style.Stroke({color: colorArr[colorindex], width: 4,opacity: 0.7
})
})
);
features.push(feature);
points = [];
}
var vectorSource = new ol.source.Vector({
features: features
});
var vector = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vector);
Upvotes: 0
Reputation: 14150
Yeap, you can use something like:
feature.setStyle(style1);
sourceFeatures.addFeature(feature);
Here is an example
Upvotes: 2