2

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);
  • Don't forget to take the Tour. For questions that involve code we ask that you show us where you are stuck with your own code by including a code snippet in your question. There is an edit button beneath your question which will enable you to do that and a {} button that enables you to format any highlighted code nicely. – PolyGeo Jul 31 '18 at 11:22
2

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)
  • Thanks :D I wasn't fully aware of the Map.remove() function or how to transfer it to layers. – Andreas Eugster Aug 3 '18 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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