I have a layer with polygons in Openlayers 4 that I want to show as polygons when zoomed in and cluster them when I zoom out to a given level.
Ol.source.Cluster has a geometryFunction attribute where I translate the polygons into points which is necessary for the Cluster object (this seems reasonable to me, the distance between polygons are not intuitive)
The problem comes when I apply a Polygon Style to the layer, since the Cluster function transforms the polygons into points it doesn't show anything, is there a way to get around this using only one layer?
var zoomedInStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
fill: new ol.style.Fill({
color: 'orange'
})
}),
geometry: function(feature) {
// Here I would need the original polygon
return feature.getGeometry().getInteriorPoint();
}
});
var zoomedOutStyle = new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'orange',
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(255, 165, 0, 0.1)'
}),
geometry: function(feature) {
var type = feature.getGeometry().getType();
if (type === 'Polygon')
return feature.getGeometry().getInteriorPoint();
}
});
function featureStyleFunction(feature, resolution) {
if (resolution > 0.5)
return zoomedOutStyle;
else
return zoomedInStyle;
};
var source = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(geoJson)
});
function clusterFunction(feature) {
return feature.getGeometry().getInteriorPoint();
};
var clusterSource = new ol.source.Cluster({
source: source,
geometryFunction: clusterFunction,
distance: 20
});
var layer = new ol.layer.Vector({
source: clusterSource,
style: featureStyleFunction
});
Best Answer
I found the solution myself, the original features that make up the clustered feature are stored in a property called "features". My zoomed in style becomes: