How can I change the color (randomly or iterate through a specific array) of a feature that I draw on the map?
This is my code:
// marker layer
Msource = new ol.source.Vector();
markLayer = new ol.layer.Vector({
source: Msource,
style: new ol.style.Style({
image: new ol.style.Icon({
opacity: 0.95,
src: 'http://www..../images/mapplot.png',
color: "red"
})
})
});
I have a button that when I click on it allows me to draw that marker with this code:
var mark;
var counter = "true";
function addMark(Type) {
counter = "true";
mark = new ol.interaction.Draw({
source: Msource,
type: Type
});
// limit the marker to 4
if (Msource.getFeatures().length < 4) {
map.addInteraction(mark);
// occurs when you finish to draw the current element
mark.on("drawend", function(){
counter = "true";
drawingMarker();
});
// occurs just after you finish to draw the current element
markLayer.on("change", function(){
map.removeInteraction(mark);
if (counter == "true") {
counter = "false";
var ind = Msource.getFeatures().length - 1;
Msource.getFeatures()[ind].setId(MarkId - 1);
}
});
} else {
map.removeInteraction(mark);
// show max marker message
$(".maxmarkers").css("display", "inline");
}
} // end addDraw
$("#Marker").click(function(e) {
e.preventDefault();
addMark("Point");
});
I use some other function like remove function and drag feature, for this reason, I assign an incremented ID.
How can I change the color of the marker randomly or through an array (the max marker are 4)?
Here a screenshot of how it looks at the moment, the marker is not red because I'm using another image at the moment but I have another (always png) that change color based on the color in the layer.
Best Answer
You may create a style function instead of giving a static style. Check this:
}