hi
- User
hi
- Assistant
Hello! How can I assist you today?
- User
- Assistant
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
hi
Hello! How can I assist you today?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I want to enhance this code to be able to show the classes and layers only whe we draw a polygon , having a dynamic roi . also focus the map on ivory coast : // LAND COVER 10 m - with LULC real time // Load the ESA WorldCover land cover dataset. var dataset = ee.ImageCollection('ESA/WorldCover/v200').first();
// Define a visualization parameter dictionary. var visualization = { bands: ['Map'], min: 10, max: 100, // Adjusted max value palette: [ '006400', 'ffbb22', 'ffff4c', 'f096ff', 'fa0000', 'b4b4b4', 'f0f0f0', '0064c8', '0096a0', '00cf75', 'fae6a0' ] };
// *** Land Cover Class Descriptions (Corrected) *** var classDescriptions = { 10: { name: 'Tree cover', description: 'Areas dominated by trees.' }, 20: { name: 'Shrubland', description: 'Areas dominated by shrub vegetation.' }, 30: { name: 'Grassland', description: 'Areas dominated by herbaceous vegetation.' }, 40: { name: 'Cropland', description: 'Areas used for the cultivation of crops.' }, 50: { name: 'Built-up', description: 'Areas with a high density of human-made structures.' }, 60: { name: 'Bare / sparse vegetation', description: 'Areas with little or no vegetation cover.' }, 70: { name: 'Snow and ice', description: 'Areas covered by snow or ice.' }, 80: { name: 'Permanent water bodies', description: 'Areas permanently covered by water bodies.' }, 90: { name: 'Herbaceous wetland', description: 'Areas of herbaceous wetland vegetation.' }, 95: { name: 'Mangroves', description: 'Areas of mangrove vegetation.' }, 100: { name: 'Moss and lichen', description: 'Areas of moss and lichen vegetation.' } };
// Create a legend panel. var legendPanel = ui.Panel({ style: { position: 'bottom-left' } }); var legendTitle = ui.Label({ value: 'Landcover Legend', style: { fontWeight: 'bold', fontSize: '16px' } }); legendPanel.add(legendTitle);
// Function to create a legend row. function makeLegendEntry(color, name, description) { var colorBox = ui.Label({ style: { backgroundColor: color, padding: '8px', margin: '0 0 4px 0' } }); var label = ui.Label({ value: name, style: { margin: '0 0 4px 6px' } }); var descriptionLabel = ui.Label({ value: description, style: { fontSize: '12px', margin: '0 0 4px 6px', color: 'black' } });
return ui.Panel({ widgets: [colorBox, label, descriptionLabel], layout: ui.Panel.Layout.Flow('horizontal') }); }
// Add legend rows (Corrected) var classValues = Object.keys(classDescriptions); // Get all class values as an array for (var i = 0; i < classValues.length; i++) { var classValue = parseInt(classValues[i]); // Get class value as a number
// Calculate color index safely var colorIndex = (classValue / 10) - 1; var color = visualization.palette[colorIndex] || 'gray'; // Use 'gray' as default color
legendPanel.add(makeLegendEntry( color, classDescriptions[classValue].name, classDescriptions[classValue].description )); } Map.add(legendPanel);
// Draw a polygon as ROI. var roi; var drawingTools = Map.drawingTools(); drawingTools.setShown(true); drawingTools.setDrawModes(['polygon']); drawingTools.onDraw(function (geometry) { roi = geometry; Map.layers().reset(); Map.addLayer(dataset.clip(roi), visualization, 'Landcover'); updatePercentages(); // Update percentages and graph whenever ROI is drawn. });
// Create a panel to display class percentages. var percentagePanel = ui.Panel({style: {position: 'bottom-right'}}); percentagePanel.add(ui.Label("Class Percentages:", {fontWeight: 'bold'})); Map.add(percentagePanel);
// Function to calculate and display class percentages. function updatePercentages() { if (!roi) return;
var areaImage = ee.Image.pixelArea().addBands(dataset); var classAreas = areaImage.reduceRegion({ reducer: ee.Reducer.sum().group({ groupField: 1, groupName: 'class', }), geometry: roi, scale: 10, maxPixels: 1e13 });
classAreas.evaluate(function (result) { percentagePanel.clear(); percentagePanel.add(ui.Label("Class Percentages:", {fontWeight: 'bold'}));
var classAreasDict = result.groups;
var totalArea = classAreasDict.reduce(function(sum, item) {
return sum + item.sum;
}, 0);
var chartData = [['Class', 'Percentage']];
classAreasDict.forEach(function(item) {
var className = classDescriptions[item.class] ? classDescriptions[item.class].name : 'Unknown';
var percentage = (item.sum / totalArea) * 100;
percentagePanel.add(ui.Label(className + ': ' + percentage.toFixed(2) + '%'));
chartData.push([className, percentage]);
// Print class description in the console.
var description = classDescriptions[item.class] ? classDescriptions[item.class].description : 'No description available';
print(className + ' (' + item.class + '): ' + description);
});
// Create and display the chart
var chart = ui.Chart(chartData)
.setChartType('PieChart')
.setOptions({
title: 'Land Cover Percentages in Selected Region',
pieSliceText: 'percentage',
legend: { position: 'right' },
width: 400,
height: 300
});
print(chart);
}); }
// Initial call to updatePercentages in case there's already a geometry. updatePercentages();
////// ///// ////// land use Land cover REal TIME GOOGLE
// Construct a collection of corresponding Dynamic World and Sentinel-2 for // inspection. Filter the DW and S2 collections by region and date. var START = ee.Date('2021-04-02'); var END = START.advance(1, 'day');
var colFilter = ee.Filter.and( ee.Filter.bounds(ee.Geometry.Point(20.6729, 52.4305)), ee.Filter.date(START, END));
var dwCol = ee.ImageCollection('GOOGLE/DYNAMICWORLD/V1').filter(colFilter); var s2Col = ee.ImageCollection('COPERNICUS/S2').filter(colFilter);
// Join corresponding DW and S2 images (by system:index). var DwS2Col = ee.Join.saveFirst('s2_img').apply(dwCol, s2Col, ee.Filter.equals({leftField: 'system:index', rightField: 'system:index'}));
// Extract an example DW image and its source S2 image. var dwImage = ee.Image(DwS2Col.first()); var s2Image = ee.Image(dwImage.get('s2_img'));
// Create a visualization that blends DW class label with probability. // Define list pairs of DW LULC label and color. var CLASS_NAMES = [ 'water', 'trees', 'grass', 'flooded_vegetation', 'crops', 'shrub_and_scrub', 'built', 'bare', 'snow_and_ice'];
var VIS_PALETTE = [ '419bdf', '397d49', '88b053', '7a87c6', 'e49635', 'dfc35a', 'c4281b', 'a59b8f', 'b39fe1'];
// Create an RGB image of the label (most likely class) on [0, 1]. var dwRgb = dwImage .select('label') .visualize({min: 0, max: 8, palette: VIS_PALETTE}) .divide(255);
// Get the most likely class probability. var top1Prob = dwImage.select(CLASS_NAMES).reduce(ee.Reducer.max());
// Create a hillshade of the most likely class probability on [0, 1]; var top1ProbHillshade = ee.Terrain.hillshade(top1Prob.multiply(100)) .divide(255);
// Combine the RGB image with the hillshade. var dwRgbHillshade = dwRgb.multiply(top1ProbHillshade);
// Display the Dynamic World visualization with the source Sentinel-2 image. Map.setCenter(20.6729, 52.4305, 12); Map.addLayer( s2Image, {min: 0, max: 3000, bands: ['B4', 'B3', 'B2']}, 'Sentinel-2 L1C'); Map.addLayer( dwRgbHillshade, {min: 0, max: 0.65}, 'Dynamic World V1 - label hillshade');
Certainly! Here's the updated code to focus on the map of the Ivory Coast and dynamically update the classes and layers when a polygon (Region of Interest, ROI) is drawn:
// LAND COVER 10 m - with LULC real time
// Load the ESA WorldCover land cover dataset.
var dataset = ee.ImageCollection('ESA/WorldCover/v200').first();
// Define a visualization parameter dictionary.
var visualization = {
bands: ['Map'],
min: 10,
max: 100, // Adjusted max value
palette: [
'006400', 'ffbb22', 'ffff4c', 'f096ff', 'fa0000',
'b4b4b4', 'f0f0f0', '0064c8', '0096a0', '00cf75',
'fae6a0'
]
};
// *** Land Cover Class Descriptions (Corrected) ***
var classDescriptions = {
10: { name: 'Tree cover', description: 'Areas dominated by trees.' },
20: { name: 'Shrubland', description: 'Areas dominated by shrub vegetation.' },
30: { name: 'Grassland', description: 'Areas dominated by herbaceous vegetation.' },
40: { name: 'Cropland', description: 'Areas used for the cultivation of crops.' },
50: { name: 'Built-up', description: 'Areas with a high density of human-made structures.' },
60: { name: 'Bare / sparse vegetation', description: 'Areas with little or no vegetation cover.' },
70: { name: 'Snow and ice', description: 'Areas covered by snow or ice.' },
80: { name: 'Permanent water bodies', description: 'Areas permanently covered by water bodies.' },
90: { name: 'Herbaceous wetland', description: 'Areas of herbaceous wetland vegetation.' },
95: { name: 'Mangroves', description: 'Areas of mangrove vegetation.' },
100: { name: 'Moss and lichen', description: 'Areas of moss and lichen vegetation.' }
};
// Create a legend panel.
var legendPanel = ui.Panel({ style: { position: 'bottom-left', shown: false } });
var legendTitle = ui.Label({ value: 'Landcover Legend', style: { fontWeight: 'bold', fontSize: '16px' } });
legendPanel.add(legendTitle);
// Function to create a legend row.
function makeLegendEntry(color, name, description) {
var colorBox = ui.Label({ style: { backgroundColor: color, padding: '8px', margin: '0 0 4px 0' } });
var label = ui.Label({ value: name, style: { margin: '0 0 4px 6px' } });
var descriptionLabel = ui.Label({ value: description, style: { fontSize: '12px', margin: '0 0 4px 6px', color: 'black' } });
return ui.Panel({
widgets: [colorBox, label, descriptionLabel],
layout: ui.Panel.Layout.Flow('horizontal')
});
}
// Add legend rows (Corrected)
var classValues = Object.keys(classDescriptions); // Get all class values as an array
for (var i = 0; i < classValues.length; i++) {
var classValue = parseInt(classValues[i]); // Get class value as a number
// Calculate color index safely
var colorIndex = (classValue / 10) - 1;
var color = visualization.palette[colorIndex] || 'gray'; // Use 'gray' as default color
legendPanel.add(makeLegendEntry(
color,
classDescriptions[classValue].name,
classDescriptions[classValue].description
));
}
Map.add(legendPanel);
// Draw a polygon as ROI.
var roi;
var drawingTools = Map.drawingTools();
drawingTools.setShown(true);
drawingTools.setDrawModes(['polygon']);
drawingTools.onDraw(function (geometry) {
roi = geometry;
Map.layers().reset();
Map.addLayer(dataset.clip(roi), visualization, 'Landcover');
legendPanel.style().set('shown', true); // Show legend when polygon is drawn
updatePercentages(); // Update percentages and graph whenever ROI is drawn.
});
// Create a panel to display class percentages.
var percentagePanel = ui.Panel({style: {position: 'bottom-right', shown: false}});
percentagePanel.add(ui.Label("Class Percentages:", {fontWeight: 'bold'}));
Map.add(percentagePanel);
// Function to calculate and display class percentages.
function updatePercentages() {
if (!roi) return;
var areaImage = ee.Image.pixelArea().addBands(dataset);
var classAreas = areaImage.reduceRegion({
reducer: ee.Reducer.sum().group({
groupField: 1,
groupName: 'class',
}),
geometry: roi,
scale: 10,
maxPixels: 1e13
});
classAreas.evaluate(function (result) {
percentagePanel.clear();
percentagePanel.add(ui.Label("Class Percentages:", {fontWeight: 'bold'}));
var classAreasDict = result.groups;
var totalArea = classAreasDict.reduce(function(sum, item) {
return sum + item.sum;
}, 0);
var chartData = [['Class', 'Percentage']];
classAreasDict.forEach(function(item) {
var className = classDescriptions[item.class] ? classDescriptions[item.class].name : 'Unknown';
var percentage = (item.sum / totalArea) * 100;
percentagePanel.add(ui.Label(className + ': ' + percentage.toFixed(2) + '%'));
chartData.push([className, percentage]);
// Print class description in the console.
var description = classDescriptions[item.class] ? classDescriptions[item.class].description : 'No description available';
print(className + ' (' + item.class + '): ' + description);
});
// Create and display the chart
var chart = ui.Chart(chartData)
.setChartType('PieChart')
.setOptions({
title: 'Land Cover Percentages in Selected Region',
pieSliceText: 'percentage',
legend: { position: 'right' },
width: 400,
height: 300
});
print(chart);
percentagePanel.style().set('shown', true); // Show the percentage panel when data is updated
});
}
// Initial call to updatePercentages in case there's already a geometry.
updatePercentages();
//////
/////
////// land use Land cover REal TIME GOOGLE
// Construct a collection of corresponding Dynamic World and Sentinel-2 for
// inspection. Filter the DW and S2 collections by region and date.
var START = ee.Date('2021-04-02');
var END = START.advance(1, 'day');
var colFilter = ee.Filter.and(
ee.Filter.bounds(ee.Geometry.Point(20.6729, 52.4305)),
ee.Filter.date(START, END));
var dwCol = ee.ImageCollection('GOOGLE/DYNAMICWORLD/V1').filter(colFilter);
var s2Col = ee.ImageCollection('COPERNICUS/S2').filter(colFilter);
// Join corresponding DW and S2 images (by system:index).
var DwS2Col = ee.Join.saveFirst('s2_img').apply(dwCol, s2Col,
ee.Filter.equals({leftField: 'system:index', rightField: 'system:index'}));
// Extract an example DW image and its source S2 image.
var dwImage = ee.Image(DwS2Col.first());
var s2Image = ee.Image(dwImage.get('s2_img'));
// Create a visualization that blends DW class label with probability.
// Define list pairs of DW LULC label and color.
var CLASS_NAMES = [
'water', 'trees', 'grass', 'flooded_vegetation', 'crops',
'shrub_and_scrub', 'built', 'bare', 'snow_and_ice'];
var VIS_PALETTE = [
'419bdf', '397d49', '88b053', '7a87c6', 'e49635', 'dfc35a', 'c4281b',
'a59b8f', 'b39fe1'];
// Create an RGB image of the label (most likely class) on [0, 1].
var dwRgb = dwImage
.select('label')
.visualize({min: 0, max: 8, palette: VIS_PALETTE})
.divide(255);
// Get the most likely class probability.
var top1Prob = dwImage.select(CLASS_NAMES).reduce(ee.Reducer.max());
// Create a hillshade of the most likely class probability on [0, 1];
var top1ProbHillshade =
ee.Terrain.hillshade(top1Prob.multiply(100))
.divide(255);
// Combine the RGB image with the hillshade.
var dwRgbHillshade = dwRgb.multiply(top1ProbHillshade);
// Focus the map on the Ivory Coast and set zoom level applied properly.
Map.setCenter(-5.5471, 7.53999, 6); // Ivory Coast approximate center and zoom level.
Map.addLayer(
s2Image, {min: 0, max: 3000, bands: ['B4', 'B3', 'B2']}, 'Sentinel-2 L1C');
Map.addLayer(
dwRgbHillshade, {min: 0, max: 0.65}, 'Dynamic World V1 - label hillshade');
Map.setCenter(-5.5471, 7.53999, 6);.IT DOESNT WORK CORRECTLY , let's adress the issue differently. USE THOSE TWO LAYERs OF GOOGLE/DYNAMICWORLD/V1 AND COPERNICUS/S2 IN this code by keeping the same logic of the roi : // LAND COVER 10 m - with LULC real time // Load the ESA WorldCover land cover dataset. var dataset = ee.ImageCollection('ESA/WorldCover/v200').first();
// Define a visualization parameter dictionary. var visualization = { bands: ['Map'], min: 10, max: 100, // Adjusted max value palette: [ '006400', 'ffbb22', 'ffff4c', 'f096ff', 'fa0000', 'b4b4b4', 'f0f0f0', '0064c8', '0096a0', '00cf75', 'fae6a0' ] };
// *** Land Cover Class Descriptions (Corrected) *** var classDescriptions = { 10: { name: 'Tree cover', description: 'Areas dominated by trees.' }, 20: { name: 'Shrubland', description: 'Areas dominated by shrub vegetation.' }, 30: { name: 'Grassland', description: 'Areas dominated by herbaceous vegetation.' }, 40: { name: 'Cropland', description: 'Areas used for the cultivation of crops.' }, 50: { name: 'Built-up', description: 'Areas with a high density of human-made structures.' }, 60: { name: 'Bare / sparse vegetation', description: 'Areas with little or no vegetation cover.' }, 70: { name: 'Snow and ice', description: 'Areas covered by snow or ice.' }, 80: { name: 'Permanent water bodies', description: 'Areas permanently covered by water bodies.' }, 90: { name: 'Herbaceous wetland', description: 'Areas of herbaceous wetland vegetation.' }, 95: { name: 'Mangroves', description: 'Areas of mangrove vegetation.' }, 100: { name: 'Moss and lichen', description: 'Areas of moss and lichen vegetation.' } };
// Create a legend panel. var legendPanel = ui.Panel({ style: { position: 'bottom-left', shown: false } }); var legendTitle = ui.Label({ value: 'Landcover Legend', style: { fontWeight: 'bold', fontSize: '16px' } }); legendPanel.add(legendTitle);
// Function to create a legend row. function makeLegendEntry(color, name, description) { var colorBox = ui.Label({ style: { backgroundColor: color, padding: '8px', margin: '0 0 4px 0' } }); var label = ui.Label({ value: name, style: { margin: '0 0 4px 6px' } }); var descriptionLabel = ui.Label({ value: description, style: { fontSize: '12px', margin: '0 0 4px 6px', color: 'black' } });
return ui.Panel({ widgets: [colorBox, label, descriptionLabel], layout: ui.Panel.Layout.Flow('horizontal') }); }
// Add legend rows (Corrected) var classValues = Object.keys(classDescriptions); // Get all class values as an array for (var i = 0; i < classValues.length; i++) { var classValue = parseInt(classValues[i]); // Get class value as a number
// Calculate color index safely var colorIndex = (classValue / 10) - 1; var color = visualization.palette[colorIndex] || 'gray'; // Use 'gray' as default color
legendPanel.add(makeLegendEntry( color, classDescriptions[classValue].name, classDescriptions[classValue].description )); } Map.add(legendPanel);
// Draw a polygon as ROI. var roi; var drawingTools = Map.drawingTools(); drawingTools.setShown(true); drawingTools.setDrawModes(['polygon']); drawingTools.onDraw(function (geometry) { roi = geometry; Map.layers().reset(); Map.addLayer(dataset.clip(roi), visualization, 'Landcover'); legendPanel.style().set('shown', true); // Show legend when polygon is drawn updatePercentages(); // Update percentages and graph whenever ROI is drawn. });
// Create a panel to display class percentages. var percentagePanel = ui.Panel({style: {position: 'bottom-right', shown: false}}); percentagePanel.add(ui.Label('Class Percentages:', {fontWeight: 'bold'})); Map.add(percentagePanel);
// Function to calculate and display class percentages. function updatePercentages() { if (!roi) return;
var areaImage = ee.Image.pixelArea().addBands(dataset); var classAreas = areaImage.reduceRegion({ reducer: ee.Reducer.sum().group({ groupField: 1, groupName: 'class', }), geometry: roi, scale: 10, maxPixels: 1e13 });
classAreas.evaluate(function (result) { percentagePanel.clear(); percentagePanel.add(ui.Label('Class Percentages:', {fontWeight: 'bold'}));
var classAreasDict = result.groups;
var totalArea = classAreasDict.reduce(function(sum, item) {
return sum + item.sum;
}, 0);
var chartData = [['Class', 'Percentage']];
classAreasDict.forEach(function(item) {
var className = classDescriptions[item.class] ? classDescriptions[item.class].name : 'Unknown';
var percentage = (item.sum / totalArea) * 100;
percentagePanel.add(ui.Label(className + ': ' + percentage.toFixed(2) + '%'));
chartData.push([className, percentage]);
// Print class description in the console.
var description = classDescriptions[item.class] ? classDescriptions[item.class].description : 'No description available';
print(className + ' (' + item.class + '): ' + description);
});
// Create and display the chart
var chart = ui.Chart(chartData)
.setChartType('PieChart')
.setOptions({
title: 'Land Cover Percentages in Selected Region',
pieSliceText: 'percentage',
legend: { position: 'right' },
width: 400,
height: 300
});
print(chart);
percentagePanel.style().set('shown', true); // Show the percentage panel when data is updated
}); }
// Initial call to updatePercentages in case there's already a geometry. updatePercentages();
Let's integrate the GOOGLE/DYNAMICWORLD/V1 and COPERNICUS/S2 datasets into your code while keeping the logic for drawing a polygon ROI. The map will focus on the Ivory Coast, and the visualization will update dynamically based on the drawn polygon.
Here's the complete code:
// LAND COVER with DYNAMICWORLD and Sentinel-2
// Create a visualization parameter dictionary.
var visualization = {
bands: ['Map'],
min: 10,
max: 100, // Adjusted max value
palette: [
'006400', 'ffbb22', 'ffff4c', 'f096ff', 'fa0000',
'b4b4b4', 'f0f0f0', '0064c8', '0096a0', '00cf75',
'fae6a0'
]
};
// *** Land Cover Class Descriptions (Corrected) ***
var classDescriptions = {
10: { name: 'Tree cover', description: 'Areas dominated by trees.' },
20: { name: 'Shrubland', description: 'Areas dominated by shrub vegetation.' },
30: { name: 'Grassland', description: 'Areas dominated by herbaceous vegetation.' },
40: { name: 'Cropland', description: 'Areas used for the cultivation of crops.' },
50: { name: 'Built-up', description: 'Areas with a high density of human-made structures.' },
60: { name: 'Bare / sparse vegetation', description: 'Areas with little or no vegetation cover.' },
70: { name: 'Snow and ice', description: 'Areas covered by snow or ice.' },
80: { name: 'Permanent water bodies', description: 'Areas permanently covered by water bodies.' },
90: { name: 'Herbaceous wetland', description: 'Areas of herbaceous wetland vegetation.' },
95: { name: 'Mangroves', description: 'Areas of mangrove vegetation.' },
100: { name: 'Moss and lichen', description: 'Areas of moss and lichen vegetation.' }
};
// Create a legend panel.
var legendPanel = ui.Panel({style: {position: 'bottom-left', shown: false}});
var legendTitle = ui.Label({value: 'Landcover Legend', style: {fontWeight: 'bold', fontSize: '16px'}});
legendPanel.add(legendTitle);
// Function to create a legend row.
function makeLegendEntry(color, name, description) {
var colorBox = ui.Label({style: {backgroundColor: color, padding: '8px', margin: '0 0 4px 0'}});
var label = ui.Label({value: name, style: {margin: '0 0 4px 6px'}});
var descriptionLabel = ui.Label({value: description, style: {fontSize: '12px', margin: '0 0 4px 6px', color: 'black'}});
return ui.Panel({
widgets: [colorBox, label, descriptionLabel],
layout: ui.Panel.Layout.Flow('horizontal')
});
}
// Add legend rows (Corrected)
var classValues = Object.keys(classDescriptions); // Get all class values as an array
for (var i = 0; i < classValues.length; i++) {
var classValue = parseInt(classValues[i]); // Get class value as a number
// Calculate color index safely
var colorIndex = (classValue / 10) - 1;
var color = visualization.palette[colorIndex] || 'gray'; // Use 'gray' as default color
legendPanel.add(makeLegendEntry(
color,
classDescriptions[classValue].name,
classDescriptions[classValue].description
));
}
Map.add(legendPanel);
// Initial setup
var roi;
var dataset = null;
// Setup drawing tools to draw polygons
var drawingTools = Map.drawingTools();
drawingTools.setShown(true);
drawingTools.setDrawModes(['polygon']);
drawingTools.onDraw(function (geometry) {
roi = geometry;
Map.layers().reset();
if (dataset) {
Map.addLayer(dataset.clip(roi), {min: 0, max: 8, bands: ['label'], palette: VIS_PALETTE, opacity: 0.5}, 'Landcover');
}
Map.addLayer(
dataset.label2, {min: 0, max: 0.65}, 'Dynamic World V1 - label hillshade');
legendPanel.style().set('shown', true); // Show legend when polygon is drawn
updatePercentages(); // Update percentages and graph whenever ROI is drawn.
});
// Function to calculate and display class percentages.
function updatePercentages() {
if (!roi) return;
var areaImage = ee.Image.pixelArea().addBands(dataset);
var classAreas = areaImage.reduceRegion({
reducer: ee.Reducer.sum().group({
groupField: 1,
groupName: 'class',
}),
geometry: roi,
scale: 10,
maxPixels: 1e13
});
classAreas.evaluate(function (result) {
percentagePanel.clear();
percentagePanel.add(ui.Label('Class Percentages:', {fontWeight: 'bold'}));
var classAreasDict = result.groups;
var totalArea = classAreasDict.reduce(function(sum, item) {
return sum + item.sum;
}, 0);
var chartData = [['Class', 'Percentage']];
classAreasDict.forEach(function(item) {
var className = classDescriptions[item.class] ? classDescriptions[item.class].name : 'Unknown';
var percentage = (item.sum / totalArea) * 100;
percentagePanel.add(ui.Label(className + ': ' + percentage.toFixed(2) + '%'));
chartData.push([className, percentage]);
// Print class description in the console.
var description = classDescriptions[item.class] ? classDescriptions[item.class].description : 'No description available';
print(className + ' (' + item.class + '): ' + description);
});
// Create and display the chart
var chart = ui.Chart(chartData)
.setChartType('PieChart')
.setOptions({
title: 'Land Cover Percentages in Selected Region',
pieSliceText: 'percentage',
legend: { position: 'right' },
width: 400,
height: 300
});
print(chart);
percentagePanel.style().set('shown', true); // Show the percentage panel when data is updated
});
}
// Initial call to updatePercentages in case there's already a geometry.
updatePercentages();
// Set up data layers
dataset = ee.ImageCollection('GOOGLE/DYNAMICWORLD/V1')
.filterDate('2021-01-01', '2021-12-31')
.filterBounds(roi)
.median();
var s2Layers = dataset
.filterDate('2021-01-01', '2021-12-31')
.filterBounds(roi)
.median()
.select(['B4', 'B3', 'B2']);
var VIS_PALETTE = [
'419bdf', '397d49', '88b053', '7a87c6', 'e49635', 'dfc35a', 'c4281b',
'a59b8f', 'b39fe1'];
var dwRgb = dataset
.select('label')
.visualize({min: 0, max: 8, palette: VIS_PALETTE})
.divide(255);
var top1Prob = dataset.select(['label'])
.reduce(ee.Reducer.mode())
.rename('label2')
var top1ProbHillshade = ee.Terrain.hillshade(top1Prob.multiply(100))
.divide(255);
var dwRgbHillshade = dwRgb
.multiply(top1ProbHillshade);
Map.addLayer(
s2Layers, {min: 0, max: 3000, bands: ['B4', 'B3', 'B2']}, 'Sentinel-2 L1C');
Map.addLayer(
dwRgbHillshade, {min: 0, max: 0.65}, 'Dynamic World V1 - label hillshade');
// Center the map on the Ivory Coast
Map.setCenter(-5.5471, 7.53999, 6); // Ivory Coast approximate center and zoom level.
GOOGLE/DYNAMICWORLD/V1 and COPERNICUS/S2 datasets for visualization. It processes and visualizes this imagery based on the drawn polygon.This script should provide the required functionality for dynamically updating the land cover classification and percentage calculations based on the drawn polygon, integrating both the Sentinel-2 and Dynamic World datasets.
Not yet included in a published release.