0

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)

1 Answer 1

1

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)
4
  • Thank you Noel...
    – MS09
    Sep 15, 2022 at 11:14
  • 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.getValue()]) } var s = ui.Select({ placeholder:'Select Layer', onChange: changeLayers}) Map.add(s)
    – MS09
    Sep 19, 2022 at 9:58
  • It is not loading any layers. What do I have to give in the select "items" to load the desired layer from the list?
    – MS09
    Sep 19, 2022 at 9:59
  • 1
    Code updated to deal with minor syntax issues. Sep 20, 2022 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.