DEV Community

Cover image for Getting Started With Google Earth Engine Functions
geedevsnairobi for geedevsnairobi

Posted on

Getting Started With Google Earth Engine Functions

Image Credits

Introduction

Welcome to GEE Functions in Javascript API.
In Google Earth engine in one way or another you will find yourself using functions either built-in or user-defined.
In this article we will be delving into using both and explore the examples in each of them.

What’s a Function?

A function is a set of instructions to perform a specific task. In Google Earth Engine,functions are blocks of code that perform specific operations on geospatial data.They
enable users to process and analyze large-scale earth observation datasets for tasks like image processing, data extraction and spatial analysis.

Code:
This refers to a set of instructions written in a programming language (in this case, JavaScript) that tells the computer what operations to perform.
Function:
A function is a block of code that performs a specific task. It takes input(s),processes them, and returns an output.
Name_of_function:
This is a user-defined name given to the function. It helps identify and call the function in the code.
Input parameters:
These are the values or data that you provide to the function for it to work on. They act as "inputs" to the function.
Call the function:
This is where you actually use the function in your code. You provide the required input parameters and execute the function.

Example:
(Input an image of the code)

// Define the function
function addNumbers(parameter_1, parameter_2){
return parameter_1 + parameter_2;
}
// Call the function
let result = addNumbers(5, 3);
console.log(result); // Output: 8

Enter fullscreen mode Exit fullscreen mode

In the above example:

  • Function: addNumbers is the name of the function.
  • Name_of_function: addNumbers
  • Input parameters: parameter_1 and parameter_2 are the input parameters. In this case, they are the numbers you want to add.
  • Call the function: let result = addNumbers(5, 3); is where we use the function. We pass 5 and 3 as inputs, and it returns 8, which is stored in the result variable.

Lets dive into variables in functions!!

Global & Local Variables

A local variable is a variable that is declared inside of a function. Unlike a global variable,a local variable may only be used inside of the function it is declared in.A variable defined outside a function is a “global variable” and is visible everywhere, including
inside functions.

We use “Return” to save the output as a global variable.

(Input Image of the same)

function calculate_divide (num1, num2) {
var diivide = ee.Number(num2).add(ee.Number(num2)); // code that calculates the
divide_test
print("Local variable, Sum, = ", diivide);
return diivide; // here we use return
}
Enter fullscreen mode Exit fullscreen mode

Now call and save the output of the function.

// Save it as a variable, Sum_test.
var divide_test = calculate_divide(5, 2);
//function call
print(The global variable, divide_test, = ,divide_test);
Enter fullscreen mode Exit fullscreen mode
  • diivide is a local variable, only meaningful within the calculate_divide function. It cannot be accessed outside of this function.
  • divide_test is a global variable, accessible throughout the entire code. It holds the value returned by calculate_divide and can be used anywhere in the code.

In-built Functions
Inbuilt functions are pre-existing functions provided by the programming language to perform commonly used operations, making it easier and more efficient for programmers to write code.
(Input Image of code)

///-------------INBUILT FUNCTIONS--------------
// This generates a list of numbers from 1 to 10.
var myList = ee.List.sequence(1, 10);
// The map() operation takes a function that works on each element independently
// and returns a value. You define a function that can be applied to the input.
var computeSquares = function(number) {
// We define the operation using the EE API.
return ee.Number(number).pow(2);
};
// Apply your function to each item in the list by using the map() function.
var squares = myList.map(computeSquares);
print(squares); // [1, 4, 9, 16, 25, 36, 49, 64, 81]

(var myList = ee.List.sequence(1, 10);) ; This line creates a list of numbers from 1 to
10. When you run this code, it gives an output of [1,2,3,4,5,6,7,8,9,10]
var computeSquares = function(number) {
// We define the operation using the EE API.
return ee.Number(number).pow(2);
};
Enter fullscreen mode Exit fullscreen mode

In the code above, we define a function named computeSquares. This function takes one parameter number. Inside the function, it uses the Earth Engine API (ee.Number(number).pow(2)) to perform an operation. It takes the input number, converts it to an Earth Engine Number, and then raises it to the power of 2, effectively squaring it.

For example,
If you call computeSquares(4), it will return 16, because 4 squared is 16.

// Apply your function to each item in the list by using the map() function.
var squares = myList.map(computeSquares);
print(squares); // [1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode
  • myList: This is the list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] that we generated using ee.List.sequence(1, 10).
  • computeSquares: This is the function we defined earlier. It takes a number as an input and returns its square.
  • myList.map(computeSquares): This applies the computeSquares function to each element in myList, resulting in a new list where each element is the square of the corresponding element in myList.
  • print(squares): This prints the resulting list, which contains the squares of the numbers in myList.

The output of the above code is:

[1, 4, 9, 16, 25, 36, 49, 64, 81]
Enter fullscreen mode Exit fullscreen mode

Final Example

// example of mapping function over a colloection
var s2 = ee.ImageCollection(COPERNICUS/S2_HARMONIZED)
.filter(ee.Filter.lt(CLOUDY_PIXEL_PERCENTAGE, 30))
.filter(ee.Filter.date(2023-01-01, 2023-03-01)
.filter(ee.Filter.bounds(geometry))
.median()
.clip(geometry)
function addIndices(image) {
var ndvi = image.normalizedDifference([B8, B4]).rename(ndvi);
var ndwi = image.normalizedDifference([B3,B8).rename(ndwi);
return image.addBands(ndvi).addBands(ndwi);
}
// Map the function over the collection
// var data = s2.map(addIndices);
print(data)
Step 1: Loading and Filtering an Image Collection
var s2 = ee.ImageCollection(COPERNICUS/S2_HARMONIZED)
.filter(ee.Filter.lt(CLOUDY_PIXEL_PERCENTAGE 30))

.filter(ee.Filter.date(2023-01-01, 2023-03-01))
.filter(ee.Filter.bounds(geometry))
.median()
.clip(geometry)
Enter fullscreen mode Exit fullscreen mode

The code above starts by loading an Image Collection from the Copernicus Sentinel-2 dataset. An Image Collection is a group of images that share a common purpose or source.

It applies a series of filters:
filter(ee.Filter.lt(CLOUDY_PIXEL_PERCENTAGE, 30)): Filters out images with
a cloudy pixel percentage greater than 30%.
filter(ee.Filter.date(2023-01-01, 2023-03-01)): Selects images within the date range of January 1, 2023, to March 1, 2023.
filter(ee.Filter.bounds(geometry)): Filters based on a specific geographic area defined by the geometry variable.
.median(): Computes the median pixel value across all the filtered images.This creates a single composite image.
.clip(geometry): Clips the resulting composite image to the boundaries defined by the geometry variable. This ensures that the image only covers a specific geographic area.

Step 2: Defining a Function

function addIndices(image) {
var ndvi = image.normalizedDifference([B8,B4]).rename(ndvi);
var ndwi = image.normalizedDifference([B3,B8]).rename(ndwi;
return image.addBands(ndvi).addBands(ndwi);
}
Enter fullscreen mode Exit fullscreen mode

This code defines a function named addIndices. A function is like a set of instructions that can be reused.
function addIndices(image): This line declares a function named addIndices
that takes a parameter image as input. The image variable represents one image from the Image Collection.
var ndvi = image.normalizedDifference([B8,B4).rename(ndvi);: Inside the
function, it calculates the NDVI (Normalized Difference Vegetation Index) and NDWI (Normalized Difference Water Index) for the input image.
return image.addBands(ndvi).addBands(ndwi);: It adds the computed NDVI and NDWI bands to the input image and returns the modified image.

In summary, the code essentially loads a filtered composite image from the Sentinel-2 dataset, then defines a function (addIndices) to calculate vegetation and water indices. This function will be applied to the s2 image.

Thanks for reading and Happy Learning. Come back later for more content on Geospatial Data Science & Remote Sensing.Cheers!!!

Top comments (0)