2

I am replicating the Hansen Global Forest Change tutorial from GEE to calculate annual forest loss by country in Africa. My code so far is:

//Country shapefiles
var countries = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017');
var Africa = countries.filter(ee.Filter.eq('wld_rgn', 'Africa'));


//Hansen Global Forest Change image with multiple bands
var gfc2014 = ee.Image('UMD/hansen/global_forest_change_2015').clip(Africa);
print("Hansen data", gfc2014);


var lossImage = gfc2014.select(['loss']); 
var lossAreaImage = lossImage.multiply(ee.Image.pixelArea()); 
Map.addLayer(lossAreaImage);

var lossYear = gfc2014.select(['lossyear']);

var lossByYear = lossAreaImage.addBands(lossYear) 
  .reduceRegions({ 
  reducer: ee.Reducer.sum()
  .group({
      groupField: 1}),
  collection: Africa, 
  scale: 30
});


print("loss by country and year", lossByYear);

When I print the feature collection, I find that the forest loss data is stored not as a property, but as a sort of sub-property, under the label "groups". How do you reclassify these variables such that they export?

Original code here, but these are all GEE datasets, so the above will run fine.

Edit update: I also tried to extract the objects by year:

var loss0 = lossByYear.map(function(f) {
  var loss2000 = ee.Feature(ee.List(f.get('groups')).get(0))
      .get('sum');
  return f.set('loss2000', loss2000);
});

And get the error: FeatureCollection (Error) Error in map(ID=00000000000000000000): Element.get, argument 'object': Invalid type. Expected: Element. Actual: Dictionary.

I also tried converting the objects as follows:



var loss = ee.FeatureCollection(ee.List(lossByYear.get('groups'))
  .map(function(el) {
    var d = ee.Dictionary(el);
    return ee.Feature(null, { yearString: ee.Number(d.get('group')).format("20%02d"), 
                              lossArea: d.get('sum'),
                              yearNumber: ee.Number(d.get('group')).add(2000)
    });
  }));

But get the error: FeatureCollection (Error) List.map: Parameter 'list' is required.

1 Answer 1

2

Try:

var addGroups = function(feature) {
  var statsFormatted = ee.List(feature.get('groups'))
  .map(function(el) {
    var d = ee.Dictionary(el);
    return [ee.Number(d.get('group')).format("20%02d"), d.get('sum')];
  });
  var statsDictionary = ee.Dictionary(statsFormatted.flatten());

  return feature.set(statsDictionary);
};

print(lossByYear.map(addGroups))
lossByYear = lossByYear.map(addGroups)
1
  • Thank you! This mapping function worked perfectly!
    – user157564
    Commented Feb 8, 2020 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.