Google Earth Engine Raster – Automate Max and Min Values of a Raster in Color Palette on Google Earth Engine

color rampgoogle-earth-enginelegendraster

Is there a way to automate my code so that Google Earth Engine can pull minimum and maximum values from a raster and update my color palette accordingly? I'm using the following code currently.

// Pull the package from the GitHub repo which stores colour palettes to be used in GEE
// See https://github.com/gee-community/ee-palettes for more info
var palettes = require('users/gena/packages:palettes');

// Choose the yellow, orange, red colour palette with 9 classes
var palette = palettes.colorbrewer.YlOrRd[9];

// Create a mask to remove 0 values
merchantable = merchantable.updateMask(merchantable.neq(0));

// Add a raster layer and enable the colour palette
Map.addLayer(merchantable, {min: 0, max: 335, palette: palette});

As you can see, the minimum value of my raster is 0, and the maximum is 335.

Best Answer

If you know the min/max values it's easy enough of course. But if you don't, and want to have the whole thing automated, you'll first need to calculate the min/max values of the image you're trying to display, and then pass those values to the visParams argument of Map.addLayer().

Here's a solution combining .reduceRegion() and .evaluate(). As your question doesn't have a reproducible example, I've used a DEM image of Switzerland as an example. Just replace those with whatever you're trying to display.

// Define region of interest
var regionOfInterest = ee.FeatureCollection("FAO/GAUL/2015/level0").filter(ee.Filter.eq('ADM0_NAME', 'Switzerland'))

// Image of interest
var img = ee.Image("WWF/HydroSHEDS/03VFDEM").clip(regionOfInterest)

// Calculate min/max values
var minMax = img.reduceRegion({reducer: ee.Reducer.minMax(), 
                               geometry: regionOfInterest, 
                               scale: img.projection().nominalScale(),
                               bestEffort: true,
                               maxPixels: 1e9})
                               
// Rename keys
var minMax = minMax.rename(minMax.keys(), ['max','min']);  

// Retrieve dictionary values and pass to visParam settings
minMax.evaluate(function(val){
  var min = val.min;
  var max = val.max;
var visParam = {
        min: min,
        max: max,
        palette: ['green', 'yellow', 'brown']
        };
        
Map.addLayer(img, visParam, "Image");
})

This returns: enter image description here