Search code examples
angularopenlayers

Openlayers different colour shapes on one layer?


So I've written the code to allow me to add shapes to the map and the draw function looks like this

  addInteraction() {
    this.coreMap.map.addInteraction(this.modifyLayer);
    this.draw = new Draw({
      source: this.vectorSource,
      style: this.style,
      type: 'Point'
    });
    this.coreMap.map.addInteraction(this.draw);
    this.snap = new Snap({source: this.vectorSource});
    this.coreMap.map.addInteraction(this.snap);
  }

Which works fine lets me draw on the map ect, however if I try and change the style on the vectorLayer to lets say from a green point to a red one it will change every dot to red rather than the new ones, I've tried a couple of things;

  • Tried pushing a new styles object into the vectorLayer.styles with setStyle([styleOneOpts, styleTwoOpts])

  • Setting the style property of the Draw property to something different which will change the cursor to said colour but the drawn point will still be the vectorLayers style colour

  • Tried creating a new Draw object and adding that as an entirely new interaction to the map

At the moment I'm presuming I'll have to create a new layer each time I want to create a new shape with a different colour, which is fine if there is no way around it but would prefer it to stay within one layer.


Solution

  • You can set a style on each newly created feature, or alternatively set a color property on each feature for example feature.set('color', 'red'); and use a style function for the layer. This would use the color set on the feature, or default to black if none was set

    style: function(feature) {
      return new Style({
    
        ...
    
          color: feature.get('color') || 'black',
    
       ...
    
      })
    }