I am using a for loop in GEE to loop over several years of data adding bands to an image (MODIS fire data). I am currently adding a band for the mean NDVI in the month the fire occurred and the previous month. However, I am struggling to get it to work for adding it to the previous month. I have used ee.Algorithms.if() so that the previous month will be 12 if it is currently 1 (so goes from January to December) and that the year becomes the previous year if the current month is January.
Make collection of NDVI with mean monthly values:
// currently values for every 16 days, take the monthly average
var month_mean = ee.List.sequence(0, 20*12).map(function(n) { // .sequence: number of years from starting year to present (Jan 2001 to Jan 2020)
var start = ee.Date('2001-01-01').advance(n, 'month'); // Starting date
var end = start.advance(1, 'month'); // Step by each iteration
return ee.ImageCollection("MODIS/006/MOD13A2").select("NDVI")
.filterDate(start, end)
.mean()
.set('system:time_start', start.millis());
});
//print(month_mean);
var meanMODINDVI = ee.ImageCollection(month_mean);
Set parameters for filtering image collections:
var startMonth = 1;
var endMonth = 12;
var startYear = 2018;
var endYear = 2019;
var d = 1;
var m = 1;
var y = 2018;
for (y; y <= endYear; y++){
for(m; m <=endMonth; m++){
//// filter fire data
var fire = ee.Image(fireCCI.filterDate(y+'-'+m+'-'+d).mosaic());
///// NDVI at time of burn
var modisNDVI = ee.Image(meanMODINDVI.filterDate(y+'-'+m+'-'+d).mosaic());
/// NDVI month previous
var j = ee.Algorithms.If(m==1, 12, m-1);
var k = ee.Algorithms.If(m==1, y-1, y);
var modisNDVIprev = ee.Image(meanMODINDVI.filterDate(k+'-'+j+'-'+d).mosaic());
var fireImageAddDate = fire.addBands(modisNDVI)
.addBands(modisNDVIprev)
.setMulti({"day":d,"month":m,"year":y});
var fireImageWithDate = ee.Image(fireImageAddDate);
}}
If I print j and k they will print the correct values, but as they are a computed object I get this error with trying to run the code:
NDVI previous month: Layer error: DateRange: Bad date/time 'ee.ComputedObject({
"type": "Invocation",
"arguments": {
"condition": false,
"trueCase": 2017,
"falseCase": 2018
},
"functionName": "If"
})-ee.Number({
"type": "Invocation",
"arguments": {
"condition": false,
"trueCase": 12,
"falseCase": 5
},
"functionName": "If"
})-1'.
I have tried casting the values using ee.Number() and ee.String() but still get the same error messages.