GEE: Calculate the areas of NDVI values above 0.2 - google-earth-engine

I am new to GEE and Javascript. I was looking for a solution to calculate the areas of NDVI values above 0.2 from the years 1989 and 2018, and quantify vegetation loss. Is this possible? I have pasted the codes below.
https://code.earthengine.google.com/48b9e089abdb51354c45333c7ea8b0f2
var MMR =
/* color: #d63000 */
/* displayProperties: [
{
"type": "rectangle"
}
] */
ee.Geometry.Polygon(
[[[112.21780240632957, 30.2114140665558],
[112.21780240632957, 29.295784619630325],
[113.23403775789207, 29.295784619630325],
[113.23403775789207, 30.2114140665558]]], null, false);
// Load 1989 and 2010 Landsat5 annual composites.
var image1989 = ee.ImageCollection("LANDSAT/LT05/C01/T1").filterDate('1989-01-01','1989-12-31')
.filterBounds(MMR)
.median()
.clip(MMR);
var image2010 = ee.ImageCollection("LANDSAT/LT05/C01/T1").filterDate('2010-01-01','2010-12-31')
.filterBounds(MMR)
.median()
.clip(MMR);
// Compute NDVI the easy way.
var ndvi1989 = image1989.normalizedDifference(['B4', 'B3']);
var ndvi2010 = image2010.normalizedDifference(['B4', 'B3']);
// Compute the multi-band difference image.
var diff = ndvi1989.subtract(ndvi2010);
var NDVI_Palette = '00FF00, FFFF00, 000000';
Map.addLayer(ndvi1989.gte(0.2), {min: -0.3, max: 0.4, palette: NDVI_Palette}, "NDVI 1989");
Map.addLayer(ndvi2010.gte(0.2), {min: -0.3, max: 0.4, palette: NDVI_Palette}, "NDVI 2010");
Map.addLayer(diff, {min: -0.3, max: 0.4, palette: NDVI_Palette}, "Difference NDVI", false);
Map.centerObject(MMR, 9);

See my answer on gis.stackexchange, where you asked the same question.
var area_1989 = ndvi1989.gte(0.2).selfMask()
.multiply(ee.Image.pixelArea())
.reduceRegion({reducer:ee.Reducer.sum(),
geometry:MMR,
scale:30,
maxPixels:1e9
})
print('Area 1989:', area_1989.get('Area'))

Related

GeometryConstructors.Polygon: LinearRing requires at least 3 points

I am trying to run the following code to extract the change map using the Land Trendr algorithm in Google Earth Engine. Everything seems to be running fine when I use a point as my area of interest, but once I try to use a polygon as my aoi file it throws me an error. I am attaching my code here :
//##########################################################################################
// START INPUTS
//##########################################################################################
// define collection parameters
var startYear = 1985;
var endYear = 2017;
var startDay = '06-20';
var endDay = '09-20';
//var aoi = ee.Geometry.Point(-122.8848, 43.7929);
var coords = ([70.9361058400289,28.387332974875402],
[83.5044652150289,28.387332974875402],
[83.5044652150289,37.305336609850876],
[70.9361058400289,37.305336609850876],
[70.9361058400289,28.387332974875402]);
var aoi = ee.Geometry.Polygon(coords);
var index = 'NBR';
var maskThese = ['cloud', 'shadow', 'snow', 'water'];
// define landtrendr parameters
var runParams = {
maxSegments: 6,
spikeThreshold: 0.9,
vertexCountOvershoot: 3,
preventOneYearRecovery: true,
recoveryThreshold: 0.25,
pvalThreshold: 0.05,
bestModelProportion: 0.75,
minObservationsNeeded: 6
};
// define change parameters
var changeParams = {
delta: 'loss',
sort: 'greatest',
year: {checked:false, start:2000, end:2010},
mag: {checked:true, value:200, operator: '\>', dsnr:false},
dur: {checked:true, value:4, operator: '\<'},
preval: {checked:true, value:300, operator: '\>'},
mmu: {checked:true, value:11},
};
//##########################################################################################
// END INPUTS
//##########################################################################################
// load the LandTrendr.js module
var ltgee = require('users/emaprlab/public:Modules/LandTrendr.js');
// add index to changeParams object
changeParams.index = index;
// run landtrendr
var lt = ltgee.runLT(startYear, endYear, startDay, endDay, aoi, index, [], runParams, maskThese);
// get the change map layers
var changeImg = ltgee.getChangeMap(lt, changeParams);
// set visualization dictionaries
var palette = ['#9400D3', '#4B0082', '#0000FF', '#00FF00', '#FFFF00', '#FF7F00', '#FF0000'];
var yodVizParms = {
min: startYear,
max: endYear,
palette: palette
};
var magVizParms = {
min: 200,
max: 800,
palette: palette
};
// display the change attribute map - note that there are other layers - print changeImg to console to see
Map.centerObject(aoi, 11);
Map.addLayer(changeImg.select(['mag']), magVizParms, 'Magnitude of Change');
Map.addLayer(changeImg.select(['yod']), yodVizParms, 'Year of Detection');
// export change data to google drive
var region = aoi.buffer(1000).bounds();
var exportImg = changeImg.clip(region).unmask(0).short();
Export.image.toDrive(
{image: exportImg,description: 'lt-gee_disturbance_map',
folder: 'lt-gee_disturbance_map',
fileNamePrefix: 'lt-gee_disturbance_map',
region: region,
scale: 30,
crs: 'EPSG:5070',
maxPixels: 1e13});
It is throwing an error: Line 75: GeometryConstructors.Polygon: LinearRing requires at least 3 points. I am not sure what I am doing wrong here. Thank you for your help.

Exporting NDWI values with Dates as CSV from Google Earth Engine

my goal is to create a csv file from the data that is chosen between dates. This was the code that I used for creating the NDWI values. I want to export that data with date so that I can create a graph from time series of NDWI - date. But I could not found how, any help is appreciated, thanks.
Map.centerObject(areaOfInterest);
Map.addLayer(areaOfInterest);
var startDate = '2018-07-01';
var endDate = '2018-07-31';
var sentinelImageCollection = ee.ImageCollection('COPERNICUS/S2')
.filterBounds(areaOfInterest)
.filterDate(startDate, endDate);
print("Number of images = ", sentinelImageCollection.size());
// We select the image with the smallest cloudy pixel percentage
var sentinelImage = sentinelImageCollection.sort('CLOUDY_PIXEL_PERCENTAGE')
.first()
.clip(areaOfInterest);
print("Sentinel image taken at = ", sentinelImage.date());
// Visualize using RGB
Map.addLayer(sentinelImage, {min: 0.0, max: 2000, bands: ['B4', 'B3', 'B2']}, 'RGB');
// Visualize using NDWI
var ndwi = sentinelImage.normalizedDifference(['B3', 'B8']).rename('NDWI');
Map.addLayer(ndwi, {palette: ['red', 'yellow', 'green', 'cyan', 'blue']}, 'NDWI');
// Calculate the area of our region of interest
var aoiArea = ee.Image.pixelArea().divide(1e6).reduceRegion({
reducer: ee.Reducer.sum(),
geometry: areaOfInterest,
scale: 10,
}).get('area');
print('AOI area (km2):', aoiArea);
// Create NDWI mask
var ndwiThreshold = ndwi.gte(0.0);
var ndwiMask = ndwiThreshold.updateMask(ndwiThreshold);
Map.addLayer(ndwiThreshold, {palette:['black','white']}, 'NDWI Binary Mask');
Map.addLayer(ndwiMask, {palette:['blue']}, 'NDWI Mask');
// We can now calculate the masked areas pixel area
var ndwiPixelArea = ee.Image.pixelArea().addBands(ndwiMask.select('NDWI')).divide(1e6).reduceRegion({
reducer: ee.Reducer.sum().group(1),
geometry: areaOfInterest,
scale: 10,
bestEffort: true
});
var list = ee.List(ee.Dictionary(ndwiPixelArea).get('groups'));
var group0 = ee.Dictionary(list.get(0));
var ndwiWaterArea = ee.Number(group0.get('sum')).float();
print("Water area (km2):", ndwiWaterArea);

I need to create an NDWI diagram in GEE, but I get an error

I want to generate a NDWI chart, but I get this error:
Error generating chart: No features contain non-null values of "system:time_start".
enter code here
var L8 = ee.ImageCollection("LANDSAT/LC08/C02/T1_RT_TOA")
.filterDate('2021-01-01', '2021-12-31')
.filterBounds(VolRn)
.filterMetadata('CLOUD_COVER', 'less_than', 1.5)
.mean()
.clip(VolRn);
var green = L8.select('B3');
var nir = L8.select('B5');
var ndwi = green.subtract(nir).divide(green.add(nir)).rename('NDWI');
var ndwiParams = {
min: -1,
max: 1,
palette: ['green', 'white', 'blue']
};
var ndwiMasked = ndwi.updateMask(ndwi.gte(0.001))
Map.setCenter(44.5858, 48.8047, 7);
Map.addLayer(ndwi, ndwiParams, 'NDWI image');
var options = {
title: 'Landsat Spectral Indexes',
hAxis: {title: 'Date'},
vAxis: {title: 'Value'},
lineWidth: 1,
maxPixels: 1e9,
series: {
0: {color: 'blue'}, // NDWI
}};
print(Chart.image.series(ndwi, VolRn, ee.Reducer.mean(), 200).setOptions(options));
enter code here
Can you please explain what this error is and how to fix it.
I am completely new to GEE and can't find information about this error.
I will be very grateful

" image.select(bands).sampleRegions is not a function error. what must i do?

I am trying to conduct a lulc classification on google earth engine using landsat5 data for 2000, but every time it is showing me the error:
image.select(bands).sampleRegions is not a function
var shp = ee.FeatureCollection(mws)
Map.addLayer(shp, {}, 'My Polygon')
var pol = ee.FeatureCollection(poly2000)
Map.addLayer(pol, {} )
//landcover for 2000//
var dataset = ee.ImageCollection("LANDSAT/LT05/C01/T1_TOA")
.filterBounds(roi1)
.filterDate('2000-01-01', '2000-01-31')
.map(function(image){return image.clip(mws)});
var trueColor432 = dataset.select(['B4', 'B3', 'B2']);
var trueColor432Vis = {};
Map.setCenter(88.41713038056656,26.861987108179317);
Map.addLayer(trueColor432, trueColor432Vis, 'True Color (432)');
var image = trueColor432;
// merging sample points together
var landcover = forest.merge(water).merge(clearing).merge(built_up);
print(landcover);
// selecting bands
var bands= ['B2','B3','B4'];
//sampling the input imagery to get a featurecollection of a training data
var training = image.select(bands).sampleRegions({
collection: landcover,
properties: ['landcover'],
scale: 30
});
//training the classifier
var classifier= ee.Classifier.svm().train({
features: training,
classProperty : 'landcover',
inputProperties: bands
});
//classifying the input imagery
var classified= image.select(bands).classify(classifier);
sampleRegions samples the pixels of an image: https://developers.google.com/earth-engine/apidocs/ee-image-sampleregions
Maybe adding .toBands() works?
var training = image.toBands().select(bands).sampleRegions({
collection: landcover,
properties: ['landcover'],
scale: 30
});

How to clip an image collection to a feature collection's geometry

I'm trying to clip an image collection to the province of Alberta, but filterBounds is not working. Thank you for any help you can offer! I would like the image collection to be clipped, not just the layer on the map, so when I perform operations on the image collection they will only be performed for Alberta
var Admins = ee.FeatureCollection("FAO/GAUL/2015/level1");
var Alberta = Admins.filter(ee.Filter.eq('ADM1_NAME', 'Alberta'));
print(Alberta)
Map.addLayer(Alberta, {}, 'Alberta')
Map.centerObject(Alberta, 6)
//Load NTL data for 2018, find the median value for each pixel
var dataset = ee.ImageCollection('NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG')
.filter(ee.Filter.date('2018-12-01', '2018-12-31'))
.filterBounds(Alberta); //here I'm trying to clip the image collection
var nighttime = dataset.select('avg_rad');
var nighttimeVis = {min: 0.0, max: 60.0};
print(nighttime)
Map.addLayer(nighttime.median(), nighttimeVis, 'Nighttime'); //this layer still shows the whole world :-(
One simple way is:
var dataset = ee.ImageCollection('NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG')
.filter(ee.Filter.date('2018-12-01', '2018-12-31'))
.map(function(image){return image.clip(Alberta)});
I figured it out. I wrote a function to clip the images and applied it over the image collection.
//Create feature for Alberta Boundary
var Admins = ee.FeatureCollection("FAO/GAUL/2015/level1");
var Alberta = Admins.filter(ee.Filter.eq('ADM1_NAME', 'Alberta'));
print(Alberta)
Map.addLayer(Alberta, {}, 'Alberta')
Map.centerObject(Alberta, 6)
//Load NTL data for 2018, find the median value for each pixel
var dataset = ee.ImageCollection('NOAA/VIIRS/DNB/MONTHLY_V1/VCMSLCFG')
.filter(ee.Filter.date('2018-12-01', '2018-12-31'))
.filterBounds(Alberta); //here I'm trying to clip the image to Alberta
function clp(img) {
return img.clip(Alberta)
}
var clippedVIIRS = dataset.map(clp)
print(clippedVIIRS)
var nighttime = clippedVIIRS.select('avg_rad');
var nighttimeVis = {min: 0.0, max: 60.0};
Map.addLayer(nighttime.median(), nighttimeVis, 'Nighttime');

Resources