I have the following example
var circle = new ol.geom.Circle([-2.59394, 51.45271], 0.001).transform('EPSG:4326', 'EPSG:3857');
//circle.transform('EPSG:4326', 'EPSG:3857');
var feature=new ol.Feature({
geometry: circle
});
var congestionLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [feature]
}),
//style: styleFunction,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255,0, 0.3)'
}),
stroke: new ol.style.Stroke({
color: '#737373',
width: 2
}),
image: new ol.style.Circle({
radius: 70,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
}),
visible: true
})
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
congestionLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([-2.59394, 51.45271]),
projection: 'EPSG:3857',
zoom: 14
})
});
where I want to change the style of the circle to have an icon of similar size, the way it should look is like this example where it's here is the draw circle interaction have the icon of matching size (like I want to do it for the first example.
You need a style function which returns an array of styles. For a circle geometry the second style is your icon positioned a the center of the circle and scaled to the circle's radius at the view resolution (adjusted for resolution and the original size of the icon). Including updateWhileAnimating
in the layer options helps to maintain scale while zooming.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="https://openlayers.org/en/v6.4.3/css/ol.css" type="text/css">
<script src="https://openlayers.org/en/v6.4.3/build/ol.js"></script>
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.map {
position: absolute;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
var circle = new ol.geom.Circle([-2.59394, 51.45271], 0.001).transform('EPSG:4326', 'EPSG:3857');
var feature=new ol.Feature({
geometry: circle
});
var style1 = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(0, 255,0, 0.3)'
}),
stroke: new ol.style.Stroke({
color: '#737373',
width: 2
})
});
var style2 = new ol.style.Style({
image: new ol.style.Icon({
src: 'https://openlayers.org/en/latest/examples/data/icon.png'
})
});
var congestionLayer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [feature]
}),
style: function(feature, resolution) {
var styles = [style1];
if (feature.getGeometry().getType() == 'Circle') {
style2.setGeometry(new ol.geom.Point(feature.getGeometry().getCenter()));
style2.getImage().setScale(feature.getGeometry().getRadius() / (40 * resolution));
styles.push(style2);
}
return styles;
},
updateWhileAnimating: true,
visible: true
})
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
congestionLayer
],
view: new ol.View({
center: ol.proj.fromLonLat([-2.59394, 51.45271]),
projection: 'EPSG:3857',
zoom: 14
})
});
</script>
</body>
</html>