Reputation: 10646
So I'm using a single vector layer where I put all of my :
This is my code :
var source = new ol.source.Vector({ wrapX: false });
var vector = new ol.layer.Vector({
source: source,
style: // styleFunction or style or [style] don't know...
});
And I want to style the feature based on their type. I found this in the documentation but can't figure out how to use it :
... A separate editing style has the following defaults:
styles[ol.geom.GeometryType.POLYGON] = [
new ol.style.Style({
fill: new ol.style.Fill({
color: [255, 255, 255, 0.5]
})
})
];
styles[ol.geom.GeometryType.LINE_STRING] = [
...
];
styles[ol.geom.GeometryType.POINT] = [
...
];
Any ideas ?
Upvotes: 2
Views: 3916
Reputation: 3081
Check the official drag/drop example -->ol3 example
It deals with every possible geometry.
So, declare your style object
var defaultStyle = {
'Point': new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: 'rgba(255,255,0,0.5)'
}),
radius: 5,
stroke: new ol.style.Stroke({
color: '#ff0',
width: 1
})
})
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#f00',
width: 3
})
}),
'Polygon': new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0,255,255,0.5)'
}),
stroke: new ol.style.Stroke({
color: '#0ff',
width: 1
})
}),
'MultiPoint': new ol.style.Style({
image: new ol.style.Circle({
fill: new ol.style.Fill({
color: 'rgba(255,0,255,0.5)'
}),
radius: 5,
stroke: new ol.style.Stroke({
color: '#f0f',
width: 1
})
})
}),
'MultiLineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#0f0',
width: 3
})
}),
'MultiPolygon': new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0,0,255,0.5)'
}),
stroke: new ol.style.Stroke({
color: '#00f',
width: 1
})
})
};
An then create your style function
var styleFunction = function(feature, resolution) {
var featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction) {
return featureStyleFunction.call(feature, resolution);
} else {
return defaultStyle[feature.getGeometry().getType()];
}
};
Finally, asign the style function to your vector layer
map.addLayer(new ol.layer.Vector({
source: new ol.source.Vector({}),
style: styleFunction
}));
Upvotes: 6
Reputation: 2944
Get the geometry type and then apply the style based on the Geometry Type
style:function(feature, resolution){
var geom_name = feature.getGeometry().getType();
return styles[geom_name];
}
})
Find the demo link https://plnkr.co/edit/kOzfXyv36UxXke8bALqU?p=preview
Upvotes: 3