Search code examples
javascriptloopsgoogle-earth-engine

Iterate over Image Collection Google Earth Enigne


I have written functions that processes all Landsat imagery and calculates NDVI. However, I have 59 GPS points, and I want a NDVI time series output per GPS point. After running my code, it seems that the resulting NDVI values are not per point, but a single value per image. I am guessing that some sort of bounding-box was automatically created and used for the calculation, instead of using the GPS points. Thus, I need to iterate my function over all 59 points, and save output into a table.

The GPS file is a ESRI points shape file.

What is the best way to do this?

Here is some of my code:

// import GPS locations from asset
GPS = GPS.geometry();

// Calculates the median NDVI and add value to image properties.
var meanNDVI = ndviLandsatCol.map(function(img) {
  var obs = img.reduceRegion({
    geometry: GPS,
    reducer: ee.Reducer.median(),
    scale: 30
  });
  return img.set('NDVI', obs.get('NDVI'));
});

The ndviLandsatCol variable is a pre-processed image collection with NDVI added as a band. I am still new to coding, and Google Earth Engine. Can someone advise on how to iterate this process over all my GPS points? How should I read in the GPS file, dictionary? And how can I save this into a .CSV without plotting the points and downloading accompanying file.

Any help would be appreciated.


Solution

  • Here is the final solution:

    // Collect GPS, image, NDVI triplets.
    var triplets = NDVILandsatCol.map(function(image) {
      return image.select('NDVI').reduceRegions({
        collection: GPS.select(['Site_ID']), 
        reducer: ee.Reducer.mean(), 
        scale: 30
      }).filter(ee.Filter.neq('mean', null))
        .map(function(f) { 
          return f.set('imageId', image.id());
        });
    }).flatten();
    print(triplets.first());
    
    // Format a table of triplets into a 2D table of rowId x colId.
    var format = function(table, rowId, colId) {
      var rows = table.distinct(rowId);
      var joined = ee.Join.saveAll('matches').apply({
        primary: rows, 
        secondary: table, 
        condition: ee.Filter.equals({
          leftField: rowId, 
          rightField: rowId
        })
      });
    
      return joined.map(function(row) {
          var values = ee.List(row.get('matches'))
            .map(function(feature) {
              feature = ee.Feature(feature);
              return [feature.get(colId), feature.get('mean')];
            });
          return row.select([rowId]).set(ee.Dictionary(values.flatten()));
        });
    };
    
    // Export table
    var table1 = format(triplets, 'imageId', 'Site_ID');
    var desc1 = 'Table_demo'; 
    Export.table.toDrive({
      collection: table1, 
      description: desc1, 
      fileNamePrefix: desc1,
      fileFormat: 'CSV'
    });