5

My app has a dateSlider that searches multiple collections, and selects the image nearest to a date within a window. I want to conditionally display those images, with error handling for empty images.

var image = l8sr
    .filterDate('2016-01-01', '2016-07-01')
    .first()

var nullImage = s2sr
  .filterDate('2016-01-01', '2016-07-01') // returns empty collection
  .first()
print(nullImage) // null



Map.addLayer(nullImage) // Error! Expression does not evaluate to an image.

// Check before trying to add the image to map  
if(nullImage !== null){Map.addLayer(nullImage)} // Same error

// Dosen't work server-side either
ee.Algorithms.If(nullImage !== null, Map.addLayer(nullImage)) // Same error

I want my script to check each image before it tries to add a layer, to avoid the error message. In other words, I want my script to be robust to handle empty image collections, so it can flexibly add layers to the map. How can I accomplish this?

https://code.earthengine.google.com/0502525f29a25d7f1d4ab7b63acde203

1
  • the dateSlider filters over multiple collections, so for example if user selects 2015 it will return a Landsat 8 image, but not a Sentinel 2 image. I only posted this toy example here for brevity.
    – cengstro
    May 9, 2021 at 17:20

1 Answer 1

5

Map.addLayer is client-side. Whether the image computation evaluates to null is server-side. So you need to bridge the gap by asking for the value to be computed:

image.evaluate(function (imageInfo) {
  if (imageInfo) {
    Map.addLayer(image);
  }
});

Note that this will also do nothing if there was an error computing the image collection for any reason; to be able to see if that's the case you need to check for an error using the second callback parameter:

image.evaluate(function (imageInfo, error) {
  if (imageInfo) {
    Map.addLayer(image);
  } else if (error) {
    print("Error:", error);
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.