1

I am using GEE for NDVI calculating. There are 150 more counties in USA. I am now stuck in outputting the NDVI ("interest" at code) of each counties listing with "OBJECTID" at the end of code. Could you please help to find the solution?

Here is the code I used.

function getNDVI_l8(image){
  return image.normalizedDifference(['B5','B4']).rename('NDVI');

}

var images_L8= ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
    .filterDate('2020-06-01', '2020-07-30')
    // .filterBounds(counties)
    .map(maskL8sr)
    .map(getNDVI_l8)
    .median().clip(counties);

Map.addLayer(images_L8,{color:'900000'});
// var interest1 = [];
for (var countyID =1; countyID < 156; countyID++){

  var shp =counties.filterMetadata('OBJECTID', 'equals', countyID);
  
  Map.addLayer(shp,{color:'900000'});
  var interest = images_L8.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: shp,
    scale: 30
  });
  // interest1 = interest.append(interest);
  print(interest);    
  
}

Export.table.toDrive({
      collection:interest,
      description:'USA_county_NDVI',
        folder:'USA_NDVI',
        fileFormat:'csv'
    });
1

When you run your code as you have it now, interest isn't filled in at all - it's set to null for every value. This is because you're mixing server- and client-side objects, which you can't do in earth engine. countyID is a client-side variable (since you initialize it using var), while the value assigned to OBJECTID is server-side. Even if their values are the same, filterMetadata will never find them to be equal because they're different types of objects.

This type of problem is one reason (but not the only one) that for-loops are generally discouraged in earth engine. Instead, you should map over counties as a FeatureCollection:

var counties = ee.FeatureCollection("TIGER/2018/Counties");

counties = counties.map(function(shp){  
  var interest = images_L8.reduceRegion({
    reducer: ee.Reducer.mean(),
    geometry: shp.geometry(),
    scale: 30,
    bestEffort: true
  });
  return shp.set('ndvi', interest);
}

That will create a new property for each element of counties and set it equal to the mean NDVI.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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