1

I am a new in GEE, trying to generate the MSAVI trends and image output for How can I fix the errors? My main objective is generate monthly MSAVI trend over the years.

This is my code:

// Import the shp
//Print the shp
 
var shp = ee.FeatureCollection (polygon)

Map.addLayer(shp, {},('Laikipia'))

// Landsat7 data
var dataset = ee.ImageCollection('LANDSAT/LE07/C01/T1_RT_TOA')
// Study period
var years = [ 2016, 2017, 2018, 2019, 2020, 2021]

// mask landsat 7 clouds 
function maskL7clouds(image) {
  var qa = image.select('BQA');

  // Bits 4 are clouds.
  var cloudBitMask = 1 << 4;

  // flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)

  return image.updateMask(mask);
}


// calculate year mean msavi2
  var datasets = dataset.filterDate('2016-01-01','2021-25-11')
  var startDate = '2016-01-01';
 var endDate = '2021-11-01';
    // Pre-filter to get less cloudy granules.
    // .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',50))
    
    // Compute the MSAVI.
var MSAVI = function(image) {
  return image.expression(
    '(2 * NIR + 1 - sqrt(pow((2 * NIR + 1), 2) - 8 * (NIR - RED)) ) / 2', 
    {
      'NIR': image.select('B4'), 
      'RED': image.select('B3'),
    }).rename('MSAVI');
};

var MSAVIvis= {min: -1, max: 1, palette: ['blue', 'white', 'green']};

//calculate the number of months to process
var nMonths = ee.Number(endDate.difference(startDate,'month')).round();

// get a list of time strings to pass into a dictionary later on
var monList = ee.List.sequence(0, nMonths).map(function (n) {
  return startDate.advance(n, 'month').format('YYYMMdd');
})
print(monList)



// map over each month
  var timeSeries = ee.List.sequence(0,nMonths).map(function (n){
    
}
    
    // calculate the offset from startDate
    var ini = startDate.advance(n,'month');
 // advance just one month
    var end = ini.advance(1,'month');
var msavi2Images = ee.ImageCollection(months.map(function(month) {
    var filtered = monthlyCol.filter(ee.Filter.eq('month', month));
    var monthlyMean = filtered.mean();
    return monthlyMean.set('month', month);
}));

         print(msavi2Images)

// Plot a time series of 
var plotMSAVI = ui.Chart.image.seriesByRegion({
  imageCollection:MSAVIcol,
  regions: shp,
  reducer:ee.Reducer.mean(),
  scale:30,
  xProperty: 'system:time_start',
  seriesProperty: 'system:index'})
  .setChartType('LineChart').setOptions({
    title: 'MSAVI laikipia',
    hAxis: {title: 'Date'},
    vAxis: {title: 'MSAVI'},
});

// Display the results.
print(plotMSAVI);
Map.addLayer(MSAVIcol.clipToCollection(shp), MSAVIvis, 'MSAVI');

1 Answer 1

1

Your code has a lot of issues, however, as you only are interested for generating the MSAVI trends and image output (with 115,252 individual images in dates range) for your large study area ('Laikipia' county in Kenya is in "FAO/GAUL/2015/level2" FeatureCollection), I could fix them as follows.

var dataset = ee.FeatureCollection("FAO/GAUL/2015/level2");

var filter = ee.Filter.inList('ADM2_NAME', ['Laikipia']);
var filteredArea = dataset.filter(filter);

//print("filteredArea", filteredArea);

var filteredArea_geom = filteredArea.first().geometry();

//print(filteredArea_geom);

Map.setCenter(36.754, 0.331, 9);

var styleParams = {
  fillColor: 'b5ffb4',
  color: '00909F',
  width: 1.0,
};

filteredArea = filteredArea.style(styleParams);

Map.addLayer(filteredArea, {}, 'Laikipia');

// Landsat7 data
var dataset = ee.ImageCollection('LANDSAT/LE07/C01/T1_RT_TOA');
// Study period
var years = [ 2016, 2017, 2018, 2019, 2020, 2021];

// mask landsat 7 clouds 
function maskL7clouds(image) {
  var qa = image.select('BQA');

  // Bits 4 are clouds.
  var cloudBitMask = 1 << 4;

  // flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0);

  return image.updateMask(mask);
}

// calculate year mean msavi2
var datasets = dataset.filterDate('2016-01-01','2017-01-01')
  .map(maskL7clouds);

var startDate = '2016-01-01';
var endDate = '2021-11-01';
    // Pre-filter to get less cloudy granules.
    // .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',50))
    
    // Compute the MSAVI.
var MSAVIcol = datasets.map(function (image) {
  
  var date = image.get('system:time_start');
  
  return image.expression(
    '(2 * NIR + 1 - sqrt(pow((2 * NIR + 1), 2) - 8 * (NIR - RED)) ) / 2', 
    {
      'NIR': image.select('B4'), 
      'RED': image.select('B3'),
    }).rename('MSAVI')
      .clip(filteredArea_geom)
      .set('system:time_start', date);
});

//print("MSAVI col", MSAVIcol.size());

var MSAVIvis= {"opacity":1,
               "bands":["MSAVI"],
               "min":0.014920102208315633,
               "max":0.5251385361565415,
               "palette":["0000ff","20ff12","008000","ff6023","ff370a"]};

var nMonths = ee.Date(endDate).difference(ee.Date(startDate), 'month').round();

//calculate the number of months to process
print("nMonths", nMonths);

// get a list of time strings to pass into a dictionary later on
var monList = ee.List.sequence(0, nMonths).map(function (n) {
  return ee.Date(startDate).advance(n, 'month').format('YYYMMdd');
});

//print("monList", monList);

// map over each month
var timeSeries = ee.List.sequence(0, nMonths).map(function (n){
    return n;
});

//print(timeSeries);

Map.addLayer(MSAVIcol, MSAVIvis, 'MSAVI col');

var MSAVIchart = 
    ui.Chart.image
        .seriesByRegion({
          imageCollection: MSAVIcol,
          band: 'MSAVI',
          // these are two geometries
          regions: [filteredArea_geom],
          reducer: ee.Reducer.mean(),
          scale: 30,
          //seriesProperty: 'label',
          xProperty: 'system:time_start'
        }).setSeriesNames(['MSAVI'])
        .setOptions({
          title: 'Average MSAVI Value by Date',
          hAxis: {title: 'Date', titleTextStyle: {italic: false, bold: true}},
          lineWidth: 2,
          colors: ['red'],
        });

print(MSAVIchart);

After running above code in GEE code editor, I got following result:

enter image description here

0

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.