Automatically naming an image for exporting to Google Drive makes more sense when we have a Feature Collection of points and a lot of images to export. The geometry (one point) considered above is going to be transformed into a Feature Collection of two points that will illustrate the iteration process if more points are considered. It looks as follows. Observe that it has a name (could be NameSite) and one id.
var pt1 = ee.Feature(ee.Geometry.Point([-105.483203125, 41.85704089594469]),
{
"name": "pt1",
"system:index": "0"
}),
pt2 = ee.Feature(ee.Geometry.Point([-96.08964045047759, 39.855638770726664]),
{
"name": "pt2",
"system:index": "1"
});
Related to the Image Collection, the dates range above considered would produce 894 elements for these two points so, I considered one year to get only 12 images to exemplify the process.
For avoiding to use the getInfo method in the exporting process, the image name will be created directly when simultaneously to map both Feature and Image collections and added to images as a property. The name of image will be composed by the date, the name site and the 'MGRS_TILE' property (to differentiate images with the same date). This name will also be used for adding and displaying the images at the Map Canvas of GEE. Complete code looks as follows:
var pt1 = ee.Feature(ee.Geometry.Point([-105.483203125, 41.85704089594469]),
{
"name": "pt1",
"system:index": "0"
}),
pt2 = ee.Feature(ee.Geometry.Point([-96.08964045047759, 39.855638770726664]),
{
"name": "pt2",
"system:index": "1"
});
var col_feats = ee.FeatureCollection([pt1, pt2]);
Map.addLayer(col_feats, {}, 'col_feats');
Map.centerObject(col_feats);
var date1 = ee.Date('2018-01-01');
var date2 = ee.Date('2019-01-01'); //'2023-01-01'
var col_img = ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
.filterDate(date1, date2);
var col_img = col_feats.map(function (ele) {
var new_col = col_img.filterBounds(ee.Feature(ele).geometry());
var setName = new_col.map(function (e) {
var name = ee.Feature(ele).get('name');
var date = ee.Date(ee.Image(e).get('system:time_start')).format().slice(0, 10);
var tile = ee.Image(e).get('MGRS_TILE');
var nameFile = ee.String('image_').cat(date)
.cat('_')
.cat(ee.String(name))
.cat('_')
.cat(tile);
return ee.Image(e).set('nameFile', nameFile);
});
return setName;
}).flatten();
print("col_img", col_img);
var exportImage = function(image, fileName) {
Export.image.toDrive({
image: image,
description: fileName,
folder: 'GEE_Folder',
region: col_feats,
fileFormat: 'GeoTIFF'
});
};
col_img.aggregate_array('nameFile').evaluate(function (fileNames) {
fileNames.forEach(function(fileName) {
var image = col_img
.filter(ee.Filter.eq('nameFile', fileName))
.first();
Map.addLayer(ee.Image(image), {}, fileName, false);
exportImage(image, fileName);
});
});
After running it at GEE code editor, I got the result of following picture. It can be observed two of the 12 images capable of being displayed and the 12 waiting export tasks.