[GIS] Getting latest image from imageCollection of Google Earth Engine

google-earth-engine

I'm trying to get the last image available in an image collection but I can't find any function that works.

I've tried also to sort the collection in the reverse order, but it doesn't work.

here is my code:

var chirps = ee.ImageCollection("UCSB-CHG/CHIRPS/PENTAD");

//get the first image and its date
var firstimg = chirps.limit(1, 'system:time_start').first();
var firstdate = ee.Date(firstimg.get('system:time_start'))
print(firstdate);

//now I try to get the latest...

chirps.sort('system:time_start', false);
var lastimg=chirps.limit(1, 'system:time_start').first();
print(ee.Date(lastimg.get('system:time_start')));

How can I get the last image available and its date in order to know which is the last date available?

Best Answer

The problem lies in 2 places.

chirps.sort('system:time_start', false);

You .sort(), but don't actually place the result in a variable. (so nothing happens)

var lastimg=chirps.limit(1, 'system:time_start').first();

The second, is when you use the .limit() function, you added the property. Which is also a sort... and by not putting a false, it went with default true.

Change your code as such and it will work.

var lastimg=chirps.limit(1, 'system:time_start', false).first();

Result:

sorted

Date (2019-08-26 00:00:00)

type: Date

value: 1566777600000

Related Question