TransWikia.com

Alternative to 'for' loop using list of strings in Google Earth Engine

Geographic Information Systems Asked on August 3, 2021

I am new to Google Earth Engine code.

Currently, I have code that runs various functions (NVDI, greenness index from Landsat data) for a single state, but for several years (using a ‘for’ loop for the years) – it generates a NDVI and other factors for 1997, 1998,…2019. I run one state, change the name, and run it again. That’s cumbersome, and since I have many states to do, so I’m hoping to automate it.

example of current code:

var startYr = 1997;
var endYr = 2019;
var roiName = 'TN'
var states = ee.FeatureCollection('my_assets/myshapefile'); // shapefile with states
var roi = ee.Feature(states.filter(ee.Filter.eq('STUSPS',roiName)).first()); // State for ROI

for (var yr = startYr; yr <= endYr; yr=yr+1){
      blah blah blah function to calculate Landsat band metrics for the roi for each year blah blah blah
}
 

Now I want to run this but not have to change the code for each state I want to run.

So I have a list of roi’s:

Example:

var states = ee.FeatureCollection('my_assets/cb_2018_CONUS_500k'); shapefile with all U.S. states
 var filtered = ee.Filter.inList('STUSPS', ['AR','MS','LA','MO','TN']); //list of states to process

I guess I’m stuck on how to "properly" do the ‘for’ loop alternative for the list of roi’s.

I’ve snipped a bunch of the code out so hopefully this makes enough sense.

One Answer

You would typically put your inputs into lists and/or collections, and iterate over them using map(). Here's an example giving your a FeatureCollection with dummy data for the years between 1997 and 2000 for two states:

var years = ee.List.sequence(1997, 2000) 
var states = ee.FeatureCollection('TIGER/2018/States')
  .filter(ee.Filter.inList('STUSPS', ['AR', 'MS']))

var features = ee.FeatureCollection(
  years.map(function (year) {
    return states.map(function (state) {
      return doSomething(year, state)
    })
  })
).flatten()

print(features)
 
function doSomething(year, state) {
  return ee.Feature(null, {
    year: year,
    state: state.get('NAME'),
    someValue: ee.Number(year).multiply(2)
  })
}

https://code.earthengine.google.com/70940120fcab694165c6bc4960a911c4

Answered by Daniel Wiell on August 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP