I'm trying to set the radius of points coming from a GeoJSON in OpenLayers. I was successful integrating the style in the style function like in this question. However, for performance reason, I now put the style outside the function to avoid repeating the style creation for each feature. The problem now is that I don't understand how to set the radius in the style with the value retrieved from the style function. I understood there is a style.setImage() function but I don't find examples how to use it for circles. Any hint on the link I'm missing here?

let style = new Style({
  image: new Circle({
    radius: r * (r / 2),
    fill: new Fill({color: 'rgba(0,0,0,0.4)'}),
    stroke: new Stroke({color: 'rgba(0,0,0,0.4)', width: 0.1})
  text: new Text({
    font: '12px sans-serif',
    fill: new Fill({color: 'rgba(0,0,0,0.8)'}),
    stroke: new Stroke({color: 'rgba(255,255,255,0.8)', width: 3}),

let styleFunction = function(feature, resolution) {
  let r = feature.get('radius')
  r = Math.round(r * 10) / 10
  return style
  • 1
    Method to change style image radius is style.getImage().setRadius(r), but since you have one style for all features, radius will change for all features that use that style.
    – TomazicM
    May 11 at 7:29
  • Great, thank you!
    – Marc
    May 11 at 7:32
  • 1
    @TomazicM As long as the style is only used in a style function setting the radius will not affect other features any more than setting the text will.
    – Mike
    May 11 at 10:14
  • @Mike Your are of course right, since style depends on feature property, not some global variable.
    – TomazicM
    May 11 at 13:16

You have two choices:

  • using style.getImage().setRadius(10);
  • cache values to create style to not instantiate one style per feature but reuse it like in https://openlayers.org/en/latest/examples/kml-earthquakes.html. This proposition suppose you will not have too many radius otherwise you may cache too many objects and mutating the radius like in first case should be better.
  • Since style is depending also on feature text, cache is probably out of question here.
    – TomazicM
    May 12 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.