To apply a function to every Image
in an ImageCollection
use
imageCollection.map()
. The only argument to map()
is a
function which takes one parameter: an ee.Image
. For example, the following
code adds a timestamp band to every image in the collection:
// Load a Landsat 8 collection for a single path-row. var collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_TOA') .filter(ee.Filter.eq('WRS_PATH', 44)) .filter(ee.Filter.eq('WRS_ROW', 34)); // This function adds a band representing the image timestamp. var addTime = function(image) { return image.addBands(image.metadata('system:time_start')); }; // Map the function over the collection and display the result. print(collection.map(addTime));
Note that in the predefined function, the metadata()
method is used
to create a new Image
from the value of a property. As discussed in the
Reducing and Compositing
sections, having that time band is useful for the linear modeling of change and for making
composites.
The mapped function is limited in the operations it can perform. Specifically, it can’t
modify variables outside the function; it can’t print anything; it can’t use JavaScript
‘if’ or ‘for’ statements. However, you can use ee.Algorithms.If()
to perform
conditional operations in a mapped function. For example:
// Load a Landsat 8 collection for a single path-row. var collection = ee.ImageCollection('LANDSAT/LC8_L1T_TOA') .filter(ee.Filter.eq('WRS_PATH', 44)) .filter(ee.Filter.eq('WRS_ROW', 34)); // This function uses a conditional statement to return the image if // the solar elevation > 40 degrees. Otherwise it returns a zero image. var conditional = function(image) { return ee.Algorithms.If(ee.Number(image.get('SUN_ELEVATION')).gt(40), image, ee.Image(0)); }; // Map the function over the collection, convert to a List and print the result. print('Expand this to see the result: ', collection.map(conditional));
Inspect the list of images in the output ImageCollection and note that the when the
condition evaluated by the If()
algorithm is true, the output contains a
constant image. Although this demonstrates a server-side conditional function (learn
more about client vs. server in Earth Engine on this page),
avoid If()
in general and use filters instead.