Google Earth Engine – How to Add Same Panel to Each Map in GEE

google-earth-engine

I'm making multiple panel apps in Google earth engine.
Could you tell me what methods are available to make the code below?

var label1 = ui.Label({
  
  value: 'title',
  style: {fontWeight: 'bold', fontSize: '18px'}
  
});

var label2 = ui.Label({
  
  value: 'content',
  style: {fontWeight: 'normal', fontSize: '18px'}

});

var selector1 = ui.Select({
  
  items: [
    {label: '-', value: 0},
    {label: '1', value: 1},
    {label: '2', value: 2},
    {label: '3', value: 3},
    {label: '4', value: 4},
  ]

}).setValue(0, false);

var Panel1 = ui.Panel([
  
    ui.Panel([label1, label2, selector1], null, {stretch:'vertical'})
  
  ]);
  
  
var map1 = ui.Map();
var map2 = ui.Map();
var map3 = ui.Map();
var map4 = ui.Map();

map1.add(Panel1);
map2.add(Panel1);
map3.add(Panel1);
map4.add(Panel1);

Best Answer

You get an error with a very clear error message:

This widget has already been added to a map.

You cannot use a widget on more than one place, you'll have to create separate ones. To prevent duplication in your code, you can use a function:

function createPanel() {
  var label1 = ui.Label({
    value: 'title',
    style: {fontWeight: 'bold', fontSize: '18px'}
  })
  
  var label2 = ui.Label({
    value: 'content',
    style: {fontWeight: 'normal', fontSize: '18px'}
  })
  
  var selector1 = ui.Select({
    items: [
      {label: '-', value: 0},
      {label: '1', value: 1},
      {label: '2', value: 2},
      {label: '3', value: 3},
      {label: '4', value: 4},
    ]
  }).setValue(0, false);
  
  return ui.Panel([
    ui.Panel([label1, label2, selector1], null, {stretch:'vertical'})
  ])
}
  
var map1 = ui.Map();
var map2 = ui.Map();
var map3 = ui.Map();
var map4 = ui.Map();

map1.add(createPanel())
map2.add(createPanel())
map3.add(createPanel())
map4.add(createPanel())

ui.root.clear()
ui.root.add(map1)
ui.root.add(map2)
ui.root.add(map3)
ui.root.add(map4)

https://code.earthengine.google.com/9ee606707fca5153679c8207a6d70c47