Google Earth Engine Legend – Rounding Numbers in a Raster Legend in Google Earth Engine

color rampgoogle-earth-enginegoogle-earth-engine-javascript-apilegendraster

I have a legend in Google Earth Engine which pulls minimum and maximum values for my raster (imported as a cloud asset).

Legend numbers

I would like to round those numbers in order to remove the decimals. It seems like ee.Number.round() is what I want. It makes sense to me to input this command after I've retrieved my rater's max and min values as shown below.

// Calculate min/max values
var minMax = image.reduceRegion({reducer: ee.Reducer.minMax(), 
                               geometry: image.geometry(), 
                               scale: image.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: palettes.colorbrewer.YlOrRd[9]
        };
        

var legendMin = ee.Number(val.min).round();
var legendMax = ee.Number(val.max).round();

var vis = {min: legendMin, max: legendMax, palette: visParam.palette}
        
// Create a mask to remove 0 values
image = image.updateMask(image.neq(0));

Map.addLayer(image, visParam, "Image");

However, that seems to break my legend.
broken legend

What would be the proper way to use the Number.round() command to get my legend numbers to exclude decimals?

Working GEE Code

Best Answer

First, visualization parameters must be client-side objects. Thus, .getInfo() is needed when defining the colormap limits in vis:

var vis = {min: legendMin.getInfo(), max: legendMax.getInfo(), palette: visParam.palette}

With this, your legend will not be 'broken' and will show the specified label ticks, which would be the rounded minimum (0), the rounded maximum (335), and the middle value (167.5). Note that the middle value is not rounded. Following your full code sample, rounding could be done using Math.round (note client-side function) when specifying the ui.Panel parameters.

var legendLabels = ui.Panel({
  widgets: [
    ui.Label(vis.min, {margin: '4px 8px'}),
    ui.Label(
        Math.round((vis.max-vis.min) / 2+vis.min),    // round this label value
        {margin: '4px 8px', textAlign: 'center', stretch: 'horizontal'}),
    ui.Label(vis.max, {margin: '4px 8px'})
  ],
  layout: ui.Panel.Layout.flow('horizontal')
});