Adding function as band to image collection in Sentinel-2

bandgoogle-earth-enginegoogle-earth-engine-javascript-apisentinel-2

I need to assess TSM in a river using Sentinel-2. Which is why I need to add the function of TSM as a new band. I used Adding multiple indices as bands to image as a guide but it is not working for my script. It doesn't show any error, but it also doesn't add the band after I map it to the collection.

Below you can find my code:

//Programar SST usando una expresion 
var SST = function (image){
           var addSST =image.expression(
          '-229.34 * ((GREEN/NIR) ** 3 )+ 1001.65 * ((GREEN/NIR) ** 2) - 1422.7 * (GREEN/NIR) +665.7',{
            'GREEN': image.select('B3'),
            'NIR':image.select('B8')
            
          }).rename('SST');
          
        return image.addBands(SST);
  
};

//SE DEBE AÑADIR LA PROPIEDAD SYSTEM:TIME_START
SST = function (image){
        return image.copyProperties(image,['system:time_start']);
  
};


var SST_IC = S2Clipped.map(SST);
print (SST_IC,'Colección Sólidos Suspendidos Totales');

Best Answer

There are a couple of issues with your script. First, you declare SST, assign it to a function. Then you reassign SST to another function. Only the second function will be used when you're mapping over the function.

Then there are problem with the functions themselves. The first one (in terms of syntax at least) correctly calculates the SST, assigns it to the variable addSST. This is a confusing naming. You typically want to name the function a verb, like addSST, and the variable a noun, like SST. A function does something, a variable is something. The problem is image.addBands(SST), where you're not adding the calculated SST to your image, but the function.

The second function doesn't actually do anything. It takes an image and reassigns the system:time_start property from the same image.

Here's how you could implement this:

var addSST = function(image) {
  var SST = image.expression(
    '-229.34 * ((GREEN/NIR) ** 3 )+ 1001.65 * ((GREEN/NIR) ** 2) - 1422.7 * (GREEN/NIR) +665.7', {
      'GREEN': image.select('B3'),
      'NIR': image.select('B8')

    }).rename('SST');

  return image.addBands(SST);
};

var SST_IC = S2Clipped.map(addSST);

https://code.earthengine.google.com/12958271968ce90c83898ed20812276d