Search code examples
angularopenlayers

How to add custom style with drag and drop in OpenLayers


I want to have custom style with open layer while using the drag & drop feature.

I did like the example and it worked, but I cannot find the way to add custom style.

Here what I've tried. (I'm using angular 11)

styles = [
    new Style({
      stroke: new Stroke({
        color: 'blue',
        width: 3,
      }),
      fill: new Fill({
        color: 'rgba(0, 0, 255, 0.1)',
      }),
    }),
    new Style({
      image: new CircleStyle({
        radius: 5,
        fill: new Fill({
          color: 'orange',
        }),
      }),
    }),
  ]

  // ...
   
  ngAfterViewInit() {
   this.map = new Map({
          interactions: defaultInteractions().extend([this.dragAndDropInteraction]),
          target: 'modal_map',
          layers: [
            new TileLayer({
              source: new OSM(),
              style: this.styles, // <-- tried to add it here but didn't worked
            }),
          ],
          view: this.view,
        })
      // ...
    }
  // ...

Solution

  • You need to set the style on the layer where the feature are added. In the linked example it would be here

    dragAndDropInteraction.on('addfeatures', function (event) {
      var vectorSource = new VectorSource({
        features: event.features,
      });
      map.addLayer(
        new VectorLayer({
          source: vectorSource,
          style: yourStyle,
        })
      );
      map.getView().fit(vectorSource.getExtent());
    });