Google Earth Engine – Using a String to Call a Geometry Name Within a Loop for Export

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

I have been trying to export some data using a loop but still could not figure out how to use the string that is in a list to define the region in the export function. I tried a few methods by searching but still could not figure this out.

var res_list = ee.List([750, 500, 250, 200, 150, 100, 90])
var region_list = ee.List(['area1', 'area2', 'area3', 'area4', 'area5'])

for (var i=0; i<7; i++){
  for (var j=0; j<5; j++){
    var res = res_list.get(i)
    var region = region_list.get(j)
    
//This ↓ is my latest attempt but did not know what I was doing

    var ROI = ee.String.evaluate(region)
    var scale = ee.Number(res).getInfo()
    // print(scale)
    var basin_name = ee.String(region).getInfo()
    var foldername = basin_name + '_sourcefiles'
    var filetype = 'DEM'
    
    
    Export.image.toDrive({
      image: elevation,
      region: ROI,
      folder: 'Sourcefiles',
      scale: scale,
      description: basin_name + '_' + filetype + '_' + scale + 'm',
      fileFormat: 'GeoTIFF',
      maxPixels: 1e13
    });
  }
}

Best Answer

In your code, you have two elements that freeze the GUI: for-loops and getInfo statements. You have to avoid both of them. For avoiding that, you can use a double loop with the evaluate method as follows. The print statement inside the more inner loop allows to corroborate that the exported images will be produced as expected.

var res_list = ee.List([750, 500, 250, 200, 150, 100, 90]);
var region_list = ee.List(["area1","area2", "area3", "area4", "area5"]);

var filetype = 'DEM';

var exportImage = function(image, fileName, res, region) {
  Export.image.toDrive({
    image: elevation,
    description: fileName,
    folder: 'GEE_Folder',
    scale: res,
    region: regions.filter(ee.Filter.eq("name", region)),
    fileFormat: 'GeoTIFF'
  });
};

res_list.evaluate(function (allRes) {

  region_list.evaluate(function (allRegions) {
    
    allRegions.forEach(function(region) {
    
      allRes.forEach(function(res) {
        var fileName = region + '_' + filetype + '_' + res + 'm';
        print(fileName);
        exportImage(elevation, fileName, res, region);

      });
    });
  });

});

Complete code can be accessed here.

After running it at GEE code editor, I got the result of following picture for 5 arbitrary geometries in USA. There are 35 tasks for all possible combinations of resolutions and geometries. At the Console Tab, you can observe the 35 printed file names in its corresponding order.

enter image description here

I downloaded and visualized two of these 35 images in QGIS and, the results are consistent with the different considered resolutions and geometries; as it can be observed in following picture:

enter image description here

Related Question