Search code examples
google-earth-engine

GEE - "NDVI" is not defined in this scope


I am new to GEE and Javascript. I'm trying to perform a simple task: calculate and visualize NDVI for January 2010 from Landsat 7. This is my code:

//Load January 2010 Data
var January = ee.ImageCollection("LANDSAT/LE07/C01/T1_RT")
.filterDate('2010-01-01', '2010-01-31');
var ls_January = ee.Algorithms.Landsat.simpleComposite(January);
var comp_January = ls_January.normalizedDifference(['B4', 
'B3']).rename('NDVI');
var NDVI_January = comp_January.select('NDVI');

var ndviVis  = {
min: 0.0,
max: 8000.0,
palette: [
'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901',
'66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01',
'012E01', '011D01', '011301'
],
};
Map.setCenter(6.746, 46.529, 2);
Map.addLayer(NDVI, ndviVis, 'NDVI'); 

The error message reads "NDVI is not defined in this scope. in , line 32 in , line 34"

I only have about 20 lines of code and made sure all blank space is deleted...

One fix I tried was to change how NDVI is calculated using GEE's own example. While this appeared to have resolved the previous error message that "NDVI is not defined in this scope," I doubt it's correct because my final map is blank. This is the modified code.

var January = ee.ImageCollection("LANDSAT/LE07/C01/T1_RT")  
.filterDate('2010-01-01', '2010-01-31');
var ls_January = ee.Algorithms.Landsat.simpleComposite(January);

var addNDVI = function(image) {
var ndvi = image.normalizedDifference(['B4', 'B3']).rename('NDVI');
return image.addBands(ndvi);
};
var NDVI = addNDVI(ls_January).select('NDVI') 

var ndviVis  = {
min: 0.0,
max: 8000.0,
palette: [
'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901',
'66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01',
'012E01', '011D01', '011301'
],
};
Map.setCenter(6.746, 46.529, 2);
Map.addLayer(NDVI, ndviVis, 'NDVI'); 

Can someone explain to me what I'm doing wrong? Thanks in advance!


Solution

  • var NDVI_January = comp_January.select('NDVI');
    ...
    Map.addLayer(NDVI, ndviVis, 'NDVI'); 
    

    The first version of your code does not work because you have not defined a variable named NDVI. Probably you want to write NDVI_January instead.

    Map.addLayer(NDVI_January, ndviVis, 'NDVI'); 
    

    Variable names are not the same as band names. Variable names never appear in quotes — they are only defined by var, function parameter lists, or imports.


    Your second script is producing all white output because your visualization max is way too high, so only the first palette entry is being used. I determined this by using the Inspector tab in the code editor: click on it, then click somewhere on the map, and you can find out what the numerical value of the bands under that pixel are.

    Change max: 8000.0, to max: 1.0, and you will be able to see some data. Then adjust it further it to suit the palette usage you're looking for.