How to Use Functions in Google Earth Engine: A Step-by-Step Guide for Beginners
Pulakesh Pradhan
PhD Scholar, MPhil, UGC-SRF (Focus Area: Climate and Agriculture || Rural Geography)
Google Earth Engine (GEE) is a powerful tool for planetary-scale environmental data analysis, and functions play a central role in writing scripts within its JavaScript-based environment. In GEE, functions help automate tasks, define workflows, and make code reusable and organized. This article will break down what a function is in GEE, the different ways to create and use functions, their components, and some practical examples.
What is a Function in Google Earth Engine?
A function in GEE is a block of code that performs a specific task. It can accept inputs (parameters), process them, and then return an output. Functions are essential for simplifying and structuring code, especially when dealing with repetitive tasks or complex analyses.
There are two main types of functions in GEE:
Anatomy of a Function in JavaScript (GEE)
A typical function in JavaScript (and thus in GEE) includes the following:
Here’s a basic example of a function structure in GEE:
// Define a function that calculates the area of a rectangle.
function calculateRectangleArea(length, width) {
var area = length * width; // Function body
return area; // Return statement
}
// Call the function and print the result
print(calculateRectangleArea(10, 5)); // Output: 50
Types of Functions in Google Earth Engine
1. Anonymous Functions
An anonymous function has no name and is often used as a “callback function,” passed as an argument to other functions. These are common when working with GEE methods like map().
Example:
var numbers = ee.List([1, 2, 3, 4]);
// Using an anonymous function in map()
var squaredNumbers = numbers.map(function(num) {
return ee.Number(num).pow(2);
});
print(squaredNumbers); // Output: [1, 4, 9, 16]
Here, the anonymous function function(num) { return ee.Number(num).pow(2); } is applied to each element in the list.
2. Named Functions
Named functions are defined with a specific name and can be reused multiple times in the script. They are helpful for readability and can be debugged more easily.
Example:
// Define a named function to add a constant value to an image
function addConstantToImage(image, constant) {
return image.add(ee.Number(constant));
}
// Apply the function to an image
var image = ee.Image(5); // Simple image with a constant value
var resultImage = addConstantToImage(image, 10);
print(resultImage); // Output: 15
Creating and Using Custom Functions
Custom functions can be useful for complex operations that involve multiple steps. Let’s go through a detailed example of creating a custom function.
领英推荐
Example: NDVI Calculation Function
The Normalized Difference Vegetation Index (NDVI) is commonly used in remote sensing for vegetation analysis. Here’s how we can create a custom function to calculate NDVI:
// Define the NDVI calculation function
function calculateNDVI(image) {
var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
return image.addBands(ndvi); // Return the image with the NDVI band added
}
// Load a Landsat 8 image
var image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318');
// Apply the NDVI function
var imageWithNDVI = calculateNDVI(image);
print(imageWithNDVI); // The image will now have an NDVI band
Function Components in GEE
Using Functions with Earth Engine Collections
Functions are frequently used with collections (like ee.ImageCollection or ee.FeatureCollection) in GEE, especially with the map() method, which applies a function to each element in the collection.
Example: Applying a Function to an Image Collection
Let’s calculate NDVI for each image in a Landsat collection over a specified area and time range.
// Define the NDVI calculation function for a collection
function addNDVIToCollection(image) {
var ndvi = image.normalizedDifference(['B5', 'B4']).rename('NDVI');
return image.addBands(ndvi);
}
// Load a Landsat ImageCollection and apply the function
var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
.filterDate('2020-01-01', '2020-12-31')
.filterBounds(ee.Geometry.Point([-122.262, 37.8719]));
// Apply the function to each image in the collection
var ndviCollection = collection.map(addNDVIToCollection);
print(ndviCollection); // Each image in the collection will now have an NDVI band
In this example, addNDVIToCollection is applied to each image in the Landsat collection.
Working with Return Types in Functions
In GEE, functions can return different types of objects like ee.Number, ee.Image, ee.Feature, or even JavaScript native types (e.g., strings or numbers). It’s important to return the correct type based on what the function is supposed to do.
Example: Custom Function to Compute and Return Mean NDVI
// Define a function to calculate mean NDVI over a region
function meanNDVI(image) {
var ndvi = image.normalizedDifference(['B5', 'B4']);
var meanNdvi = ndvi.reduceRegion({
reducer: ee.Reducer.mean(),
geometry: ee.Geometry.Point([-122.262, 37.8719]),
scale: 30
});
return meanNdvi.get('nd');
}
// Load an image and calculate mean NDVI
var image = ee.Image('LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318');
var meanNdviValue = meanNDVI(image);
print(meanNdviValue); // Output: mean NDVI value at the specified point
Tips for Using Functions in Google Earth Engine
Conclusion
Functions in Google Earth Engine are essential for managing complex workflows, making code modular, and reducing redundancy. From simple calculations to applying transformations across large datasets, functions make it possible to work efficiently and effectively with massive geospatial datasets in GEE. By understanding the syntax and types of functions available, you can write robust and flexible code for advanced geospatial analysis.
?? More insights & projects: pulakeshpradhan.github.io
Oceanography Student of Dept. Of Marine Sciences, Berhampur University|
1 天前Very helpful