google-earth-engine – Selection and Layer Loading with Google Earth Engine JavaScript API

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

I have created a simple ui.select() menu and want the app to load the desired layer upon selection. This is my code, this code is not working and second thing is that I don't want to do if else statements, rather is there any other function that will load the selected layer.
https://code.earthengine.google.com/11bc12da755b5d87ba00c73bca209c69

var SRTM = ee.Image("CGIAR/SRTM90_V4");
var slope = ee.Terrain.slope(SRTM);

function changeLayers(x){
  // get value from list
  var value =  x.getValue();
  if(value=="SRTM"){
    Map.addLayer(SRTM);
  }
  else if(value=="Slope"){
    Map.addLayer(slope)
  }
}
var select = ui.Select({
  items: ee.List(['SRTM','Slope']), placeholder:'Select',onChange:changeLayers()})
Map.add(select)

Best Answer

The onChange specification is improper; you shouldn't use () there, that actually calls the function. Instead, you just want to specify the function to call (essentially, just its name):

var select = ui.Select({
  items: ee.List(['SRTM','Slope']), placeholder:'Select',onChange:changeLayers})

To avoid the if/else, use a dictionary.

var layers = {
    SRTM: ee.Image("CGIAR/SRTM90_V4");
    Slope: ee.Terrain.slope(ee.Image("CGIAR/SRTM90_V4"));
}
function changeLayers(x) {
  Map.layers().reset([layers[x]]) 
} 
var s = ui.Select({items: Object.keys(layers), placeholder:'Select Layer', onChange: changeLayers})
Map.add(s)