[GIS] Google Earth Engine – remove layer from the layer manager

google-earth-engine

Is there a way in Google Earth Engine to remove layers which are in the layer manager?

Example:

//Image selection
var img1 = ee.Image('COPERNICUS/S2/20161231T035142_20161231T040436_T47PNP')

//Location
var center = ee.Geometry.Point(99.256, 12.1682)
Map.addLayer(center,'','Center')
Map.centerObject(center,10);

//color palette
var rgb_vis = {min:0, max:3000, bands:['B4','B3','B2']};

//add images to map
Map.addLayer(img1,rgb_vis,'Image 1',true);

//NDVI Button
var button = ui.Button({
  label: 'Calculate NDVI',
  onClick: function() {
    var NDVIimg1 = img1.normalizedDifference(['B8', 'B4'])
    Map.addLayer(NDVIimg1,'','NDVI',true)
  }
});
print(button);

I would like to get rid of the layer "Image 1" in the layer manager, but the centerpoint should stay. Is there a better way than put a Map.clear() in the button code and re-add the centerpoint again?

//NDVI Button
var button = ui.Button({
  label: 'Calculate NDVI',
  onClick: function() {
    Map.clear()
    var NDVIimg1 = img1.normalizedDifference(['B8', 'B4'])
    Map.addLayer(center,'','Center')
    Map.addLayer(NDVIimg1,'','NDVI',true)
  }
});
print(button);

Best Answer

Yes, there is a way:

var removeLayer = function(name) {
  var layers = Map.layers()
  // list of layers names
  var names = []
  layers.forEach(function(lay) {
    var lay_name = lay.getName()
    names.push(lay_name)
  })
  // get index
  var index = names.indexOf(name)
  if (index > -1) {
    // if name in names
    var layer = layers.get(index)
    Map.remove(layer)
  } else {
    print('Layer '+name+' not found')
  }
}

It's available in geetools:

// import tools
tools = require('users/fitoprincipe/geetools:tools')

// use function
tools.removeLayer(name)
Related Question