google-earth-engine – How to Change Image on Map Using Slider in Google Earth Engine

google-earth-enginegoogle-earth-engine-javascript-api

I want to switch between map layers in Google Earth Engine using a slider. The idea is to set the opacity of the layers iteratively, like in this app:
https://nrtwur.users.earthengine.app/view/raddalert

Here's a simple example:

// Some layers.
var l0 = ui.Map.Layer({eeObject: ee.Image(1), opacity: 1}); // Initially, only this one will be shown.
var l1 = ui.Map.Layer({eeObject: ee.Image(1), opacity: 0});
var l2 = ui.Map.Layer({eeObject: ee.Image(1), opacity: 0});
var l3 = ui.Map.Layer({eeObject: ee.Image(1), opacity: 0});
var l4 = ui.Map.Layer({eeObject: ee.Image(1), opacity: 0});

// Adding layers to the Map.
Map.layers().set(0, l0);
Map.layers().set(1, l1);
Map.layers().set(2, l2);
Map.layers().set(3, l3);
Map.layers().set(4, l4);

// Layer list
var layerList = Map.layers();
print(layerList);

// Slider to define which image will be shown.
var slider = ui.Slider({
  min: 0, 
  max: layerList.length() - 1, 
  value: 0, 
  step: 1
});

Map.add(slider);

// Function that changes the opacity of layers
slider.onSlide(); // ???

https://code.earthengine.google.com/21a6281d1a93c9e3e1b7b90dc216702b?noload=true

The idea is:

  1. Set the minimum and maximum value of the slider according to the number of images to be displayed. If I have 5 layers then the min and max values should be 0 and 4 respectively.

  2. The slider's value property changes the image being shown on the map.

I know I can get the answer by iteratively changing the opacity of the layers, but I couldn't implement the idea in GEE.

Best Answer

The trick is to save what the previously selected image was so you can easily set the Image to transparent. For this I use the variable current. Then you can get the newly selected Image from the layer list and set the opacity to 1.

var current = 0
// Slider to define which image will be shown.
var slider = ui.Slider({
  min: 0, 
  max: layerList.length() - 1, 
  value: current, 
  step: 1
});

Map.add(slider);

// Function that changes the opacity of layers
slider.onSlide(function(value){
  layerList.get(current).setOpacity(0);
  layerList.get(value).setOpacity(1);
  current = value
});
Related Question