Google Earth Engine – How to Name Layer with Date of the Image in Google Earth Engine

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

I want to map a layer in Google Earth Engine and the layer name should be the date the image was taken. I created a variable with the date as a string, but I always get the error that the layer name would not be a string.

Can anyone help me with this or is there a better solution to get the date as a string instead of my rather complicated way?

I am quite new with GEE.

Here is the code snippet:

var year = ee.Image(s1).getString('system:index').slice(-50, 21);
var month = ee.Image(s1).getString('system:index').slice(-46, 23);
var day = ee.Image(s1).getString('system:index').slice(-44, 25);
                            
var date = ee.String(year.cat('-').cat(month).cat('-').cat(day))

var addDate = s1.set({'Date': date});
print('Image', addDate)

var layerName = addDate.get('Date');
print('Layer name:', layerName)

Map.addLayer(addDate, '', 'Image')
Map.addLayer(addDate, '', date)

And here is my script

Later, I want to implement this into a function for an image collection to map several images automatically with individual layer names.

Best Answer

This fails because date is a server-side object, and Map.addLayer() expects name to be client-side. Read up on the difference here. You can turn server-side objects into client-side with evaluate().

date.evaluate(function (clientDate) {
  Map.addLayer(addDate, '', clientDate)
})

https://code.earthengine.google.com/1bc186fff8d06816861da6238577c213

Related Question