Reputation: 148
I am using OpenLayers with Javascript and showing clustered features on map. I would like to change the icon of the feature within a cluster according to one of its attributes value.
var style1 = new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 66],anchorXUnits: 'fraction',anchorYUnits: 'pixels',
opacity: 0.85,src: 'https://img.icons8.com/flat_round/64/000000/home.png',scale: 0.3
}));
var style2 = new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 66],anchorXUnits: 'fraction',anchorYUnits: 'pixels',
opacity: 0.85,src: 'https://img.icons8.com/color/48/000000/summer.png',scale: 0.3
}));
function myStyleFunction(feature) {
let props = feature.getProperties();
if (props.id>50) {
console.log(props.id);
return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
} else {
console.log(props.id);
return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
}
};
In the code above, i want to access the property "id" of one of the features within the cluster and set its icon based on the "id" value. However, I can't get the feature property.
Here is a codepen. I would appreciate anyone's help.
Upvotes: 0
Views: 2050
Reputation: 17972
If you only check the first feature in each cluster:
function myStyleFunction(feature) {
let props = feature.get('features')[0].getProperties();
if (props.id>50) {
console.log(props.id);
return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
} else {
console.log(props.id);
return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
}
};
If you want to find the value in any feature in the cluster
function myStyleFunction(feature) {
let maxId = 0;
feature.get('features').forEach(function(feature){
maxId = Math.max(maxId, feature.getProperties().id);
});
if (maxId>50) {
console.log(maxId);
return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
} else {
console.log(maxId);
return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
}
};
For an ol-ext cluster
function myStyleFunction(feature) {
let id = 0;
let features = feature.get('features');
if (features) {
id = features[0].get('id');
}
if (id > 50) {
return new ol.style.Style({image: style1,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
} else {
return new ol.style.Style({image: style2,stroke: new ol.style.Stroke({ color:"#fff", width:1 }) });
}
};
Upvotes: 1