I want to set a text and color for each marker with JSON data when I append them to map. This example code is fine. Text and color are static at the moment. Can I do it with some function or maybe should I change the syntax to make it work?
const vectorSource = new ol.source.Vector();
const vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
image: new ol.style.Circle({
radius: 18,
fill: new ol.style.Fill({
color: [0, 155, 0, 0.6]
}),
stroke: new ol.style.Stroke({
color: [0, 200, 0, 0.9],
width: 3
})
}),
text: new ol.style.Text({
text: "Test",
scale: 1.2,
fill: new ol.style.Fill({
color: "#fff"
}),
stroke: new ol.style.Stroke({
color: "0",
width: 3
})
})
})
})
vectorLayer.setZIndex(5);
const map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
),
vectorLayer
],
target: "map",
view: new ol.View({
center: [0, 0],
zoom: 5
})
});
const addMarkers = (lat, long) => {
if(lat && lat !== 0) {
const point = new ol.geom.Point(ol.proj.transform([lat, long], "EPSG:4326", "EPSG:3857"));
const iconFeature = new ol.Feature({
geometry: point
});
vectorSource.addFeature(iconFeature);
}
}
// Positions come from map.jade
positions.forEach(position => {
let long = position.geolocation.longitude;
let lat = position.geolocation.latitude;
if (long !== 0 && long !== 999.9 && long !== "" && long !== undefined) {
addMarkers(long, lat);
}
});
In the ol.layer.Vector constructor, instead of passing an ol.style.Style instance, you can pass a function.
That function will receive feature and resolution and shall return an ol.style.Style object.
Here's an example: http://openlayersbook.github.io/ch06-styling-vector-layers/example-07.html
Otherwise, you can use the ol.Feature.setStyle function inside the addMarkers function.