Google Earth Engine Tutorial: Beginners Guide 2 JavaScript API Basics
Credit: Youtube Channel “Terra Spatial, Fundamental tutorial on using JavaScript API within Google Earth Engine for basic scripting and operations.”
You can see all the tutorials from here: Techgeo Academy.
Google Earth Engine Tutorial: Beginners Guide to JavaScript API Basics
Google Earth Engine (GEE) is a powerful cloud-based platform that provides planetary-scale environmental data and analysis capabilities. This tutorial will introduce you to the fundamentals of using the JavaScript API, the primary programming interface for Earth Engine.
Getting Started with Google Earth Engine JavaScript API
To begin working with Earth Engine’s JavaScript API, you’ll need to access the Code Editor at code.earthengine.google.com. The interface includes:
- Code Editor panel for writing scripts
- Console for viewing outputs
- Map display area
- Inspector tool for examining map features
- Tasks panel for managing export operations
Basic JavaScript Concepts for Earth Engine
Variables and Assignment
In Earth Engine, you’ll work with server-side objects that are created and manipulated differently from regular JavaScript variables.
// Creating Earth Engine objects var image = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20140318'); var geometry = ee.Geometry.Point([-122.082, 37.422]); var number = ee.Number(42);
Object Methods and Chaining
Earth Engine objects have methods that can be chained together for complex operations:
var filteredCollection = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2') .filterBounds(geometry) .filterDate('2020-01-01', '2020-12-31') .sort('CLOUD_COVER') .limit(10);
Working with Images
Loading and Displaying Images
// Load a Landsat 8 image var image = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20140318'); // Display the image Map.addLayer(image, {bands: ['SR_B4', 'SR_B3', 'SR_B2'], min: 0, max: 3000}, 'Landsat Image'); // Center the map on the image Map.centerObject(image, 8);
Image Processing Operations
// Calculate NDVI var nir = image.select('SR_B5'); var red = image.select('SR_B4'); var ndvi = nir.subtract(red).divide(nir.add(red)).rename('NDVI'); // Add NDVI layer to map Map.addLayer(ndvi, {min: -1, max: 1, palette: ['blue', 'white', 'green']}, 'NDVI');
Image Collections
Image collections are groups of images that share common properties:
// Load a Landsat 8 collection var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2') .filterDate('2020-06-01', '2020-09-01') .filterBounds(Map.getCenter()) .select(['SR_B2', 'SR_B3', 'SR_B4', 'SR_B5']); // Get collection information print('Collection size:', collection.size()); print('First image:', collection.first());
Filters and Queries
Earth Engine provides various filtering options for collections:
var filtered = collection .filterBounds(geometry) // Filter by location .filterDate('2020-01-01', '2020-12-31') // Filter by date .filterMetadata('CLOUD_COVER', 'less_than', 20) // Filter by metadata .sort('CLOUD_COVER') // Sort by property .limit(5); // Limit results
Geometries and Features
Creating Geometries
// Point geometry var point = ee.Geometry.Point([-122.082, 37.422]); // Polygon geometry var polygon = ee.Geometry.Polygon([ [[-122.085, 37.425], [-122.085, 37.420], [-122.075, 37.420], [-122.075, 37.425]] ]); // Display geometries Map.addLayer(point, {color: 'red'}, 'Point'); Map.addLayer(polygon, {color: 'blue'}, 'Polygon');
Reductions and Statistics
Reductions compute statistical summaries of images or collections:
// Calculate image statistics var stats = ndvi.reduceRegion({ reducer: ee.Reducer.mean(), geometry: polygon, scale: 30, maxPixels: 1e9 }); print('NDVI mean:', stats.get('NDVI'));
Mappings and Iterations
Apply functions to each image in a collection:
// Function to calculate NDVI for each image var addNDVI = function(image) { var ndvi = image.normalizedDifference(['SR_B5', 'SR_B4']).rename('NDVI'); return image.addBands(ndvi); }; // Apply the function to each image in the collection var collectionWithNDVI = collection.map(addNDVI);
Visualization and Export
Visualization Parameters
var visParams = { bands: ['SR_B4', 'SR_B3', 'SR_B2'], min: 0, max: 3000, gamma: 1.4 }; Map.addLayer(image, visParams, 'Landsat RGB');
Exporting Data
// Export image to Google Drive Export.image.toDrive({ image: ndvi, description: 'NDVI_export', folder: 'EarthEngine', fileNamePrefix: 'ndvi_map', region: polygon, scale: 30, maxPixels: 1e13 });
Frequently Asked Questions
What is the difference between client-side and server-side objects in Earth Engine?
Client-side objects are regular JavaScript variables that work immediately, while server-side objects (prefixed with ee.) are sent to Google’s servers for processing. Server-side objects must be evaluated before their values can be accessed, typically through print() statements or by exporting data.
How do I handle large datasets without hitting memory limits?
Use appropriate scale parameters in your analyses, limit the spatial extent of your computations, use reduceRegion() with appropriate reducers instead of getting individual pixel values, and break large operations into smaller chunks using mapping functions.
Why don’t my calculations show up immediately?
Earth Engine uses lazy evaluation, meaning computations are only executed when data is explicitly requested (like with print() or export operations). Complex operations build a computation graph that’s executed only when necessary.
How can I speed up my Earth Engine scripts?
Apply spatial and temporal filters early to reduce dataset size, use appropriate scale parameters for your analysis, avoid unnecessary operations, use server-side functions when possible instead of client-side loops, and consider using Export operations for intensive computations.
What are the common debugging strategies in Earth Engine?
Use print() statements extensively to inspect objects and values, utilize the console for error messages, check that all required parameters are correctly specified, ensure geometries and images intersect properly, and verify that date ranges are appropriate for your datasets.
How do I cite Earth Engine in my research?
You can cite Earth Engine using this format: Gorelick, N., Hancher, M., Dixon, M., Ilyushchenko, S., Thau, D., & Moore, R. (2017). Google Earth Engine: Planetary-scale geospatial analysis for everyone. Remote sensing of Environment, 202, 18-27.
Can I use Earth Engine offline?
The web-based Code Editor requires internet connectivity, but you can use the Python API locally with the earthengine-api Python package. Some data can be exported for offline use, but real-time computation always requires cloud connectivity.
What is the difference between Image.select() and Image.pick()
Image.select() extracts specific bands by name, while Image.pick() is not a standard Earth Engine method. Use select() when you know the band names you want to work with, and it’s generally the method you want for band manipulation.
Conclusion
This beginner’s guide covers the essential concepts of Earth Engine’s JavaScript API. As you become more comfortable with these basics, you can explore advanced topics like time series analysis, machine learning applications, and large-scale geospatial processing. Remember to start with simple operations and gradually build complexity in your analyses.
Practice is key to mastering Earth Engine – experiment with different datasets, try modifying the examples provided, and don’t hesitate to consult the comprehensive Earth Engine documentation and community forums for additional support.