Search code examples
javascriptopenlayersopenlayers-6

OpenLayers ->Points on the map are flashing on and off constantly. Is there a way to stop this behaviour?


I have edited Open Layer's "Icon Symbolizer"([https://openlayers.org/en/latest/examples/icon.html]) example for my case and latest code is different until layer definition part(line 35 on example code). Rest of the code will be same with the example.

Question is: When I put too much different colors with different features I get flashing points instead of showing all points constantly. Is there a way to solve this issue?

Any help on this is appreciated...

function getRandForCoordinates(from, to, fixed) {
  return (Math.random() * (to - from) + from).toFixed(fixed) * 1;
}

function GetVectors() {
  let icons = [];
  for (let i = 0; i < 850; i++) {
    
    icons[i] = new Feature({
      geometry: new Point([getRandForCoordinates(-180, 180, 3)*500, getRandForCoordinates(-180, 180, 3)*5000]),
      name: 'Null Island',
      population: 4000,
      rainfall: 500,
    });
  }

  return new VectorSource({
    features: icons,
  });
}

function StyleBuilder() {
  var MyColor =
    'rgba(' +
    Math.floor(Math.random() * 254) +
    ',' +
    Math.floor(Math.random() * 254) +
    ',' +
    Math.floor(Math.random() * 254) +
    ',' +
    1 +
    ')';
  return new Style({
    image: new Icon({
      color: MyColor,
      crossOrigin: 'anonymous',
      src: 'data/icon.png',
    }),
  });

}

const vectorLayer = new VectorLayer({
  source: GetVectors(),
  style: StyleBuilder,
});
  1. I tried to give only one color and it was working as expected however I will need multiple colors.
  2. I have tried to give style on feature definition. It gave me same result. Like in this function:
function GetVectors() {
  let icons = [];
  for (let i = 0; i < 850; i++) {
    
    icons[i] = new Feature({
      geometry: new Point([getRandomInRange(-180, 180, 3)*500, getRandomInRange(-180, 180, 3)*5000]),
      name: 'Null Island',
      population: 4000,
      rainfall: 500,
    });

    icons[i].setStyle(StyleBuilder);
  }

  return icons;
}

Solution

  • Using a function as a style recalculates the style each time the feature is rendered.

    If you set the style with the result of the function it is only called once for each feature

    function GetVectors() {
      let icons = [];
      for (let i = 0; i < 850; i++) {
        
        icons[i] = new Feature({
          geometry: new Point([getRandomInRange(-180, 180, 3)*500, getRandomInRange(-180, 180, 3)*5000]),
          name: 'Null Island',
          population: 4000,
          rainfall: 500,
        });
    
        icons[i].setStyle(StyleBuilder());
      }
    
      return icons;
    }