0

I am trying to create imageCollections for several regions in a loop in GEE.

I am struggling with assigning them to individual variables which are available after exiting the loop. So far, after exiting the loop, the ImageCollection "sentinelCollection" naturally only contains the images of the last processed region.

How can I loop through the regions and create a uniquely named imageCollection for each of them?

I am just starting using GEE, sorry if this is a very basic question but I did not find any information on this.

// Define the regions of interest as a feature collection, 
// with "regions" being my dataset which contains several polygons
 var roi = regions;

// Define a list of region names
var regionNames = ["LVha-1", "LVha-2"];

// Loop through the region names and load the Sentinel-2 images for each region
for (var i = 0; i < regionNames.length; i++) {
  var regionName = regionNames[i];
  var region = roi.filterMetadata("Region", "equals", regionName);

  // Load Sentinel-2 image collection for the region
  var sentinelCollection = ee.ImageCollection("COPERNICUS/S2_SR")
    .filterBounds(region)
    .filterDate("2018-05-01", "2018-10-31");

  print(sentinelCollection, regionName)
}

1 Answer 1

2

You cannot dynamically create variables. If you want a variable for each collection, you can create a function to minimize duplication.

var collectionLVha1 = toCollection('LVha-1')
var collectionLVha2 = toCollection('LVha-2')

function toCollection(regionName) {
  var region = roi.filterMetadata("Region", "equals", regionName)
  return ee.ImageCollection("COPERNICUS/S2_SR")
    .filterBounds(region)
    .filterDate("2018-05-01", "2018-10-31")
}
1
  • Thanks a lot, this worked! I find it kind of odd, it is not possible to dynamically create variables as this is quite a common thing in Python or also R and probably a bunch of other languages... Can you tell me the reason, why it is not possible using JavaScript?
    – pottsbill
    Apr 6 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.