Search code examples
javascriptangulartypescriptsingle-page-applicationopenlayers

Open layers Angular how to adjust opacity with a slider


I have a map thats generated on the components init that runs a method called makeMap() that creates a map that looks like follows

makeMap() {

  var osm = new TileLayer({
    source: new OSM(),
  });

  ...

  this.map = new Map({
    layers: [osm, wktLayer, this.tiles],
    target: 'ol-map',
    view: new View({
      center: proj.fromLonLat(coordinates),
      zoom: 9,
      minZoom: 8.75,
    }),
  });
}

I am trying to add a slider on the front end that can adjust the opacity of the layer "this.tiles". I have the following html for a slider. for testing right now im trying to adjust it as follows.

  setOpacity() {
    this.tiles.setOpacity(0);
    this.map.render()
  }

the issue is when I try to call the method after the map is created it doesnt update the layer only if I call it before its made. Im trying to connect it to a slider as follows

      <input
        id="opacity-input"
        type="range"
        min="0"
        max="1"
        step="0.01"
        value="1"
      />

How can I update the opacity of the layer when the slider changes value? I am new to angular and openlayers so im not sure how to create this functionality.


Solution

  • Works for me like this with react:

    <RangeInput onValueChanged={(value) => handleOpcitry(value)} />
    
    const handleOpcitry = useCallback(
        (value: number) => {
          if (!osmLayer) {
            return;
          }
    
          const opacity = value / 100;
    
          console.log(opacity);
    
          osmLayer.setOpacity(opacity);
        },
        [osmLayer]
      );
    

    Range Input:

    <input
            type="range"
            min="0"
            max="100"
            value={100}
            onChange={handleValueChange}
    ></input>