Google Earth Engine – How to Control Null Features in GEE?

google-earth-enginegoogle-earth-engine-javascript-api

In this simple example, I want to select a polygon using Map.OnClick. When I select a polygon, there is not a problem.

I want to create an error handling process for null features. When I click on the map which is not bounding with clicked point, I want to control null feature.

I found an approach of Gennadii Donchyts and it is working. It is using size of features for controlling null features.

Why didn't the second approach work? When I printed clickedPolygon variable value, the result is null.

var gaul = ee.FeatureCollection("FAO/GAUL_SIMPLIFIED_500m/2015/level1")
var table = gaul.filter(ee.Filter.eq('ADM0_NAME', 'Turkey'))
  
Map.addLayer(table)
Map.centerObject(table,7)
  
Map.style().set({cursor: 'crosshair'});  
    
Map.onClick(function(coords) {  
  coords = ee.Dictionary(coords)
  var lon = coords.get('lon')
  var lat = coords.get('lat')
  var pt = ee.Geometry.Point([lon, lat])
  var clickedPolygon = table.filterBounds(pt)
    
  // first approach : IT IS WORKING (Gennadii Donchyts)
  clickedPolygon.size().evaluate(function(size) {
    if(size) {
      Map.centerObject(clickedPolygon)
      print(clickedPolygon)                
      return
    } else {
      print(clickedPolygon)  
      print('Please, click on a polygon to select')  
    }
  })
    
  // second approach : IT ISN'T WORKING
  clickedPolygon= clickedPolygon.first() 
  if (clickedPolygon === null) {
    print(clickedPolygon) 
    print('clickedPolygon is null')
  }        
})

Best Answer

You might be mixing understanding of server vs client side of scripts. It can seem tricky at first. If-statement is client side, and EE operations are server side. You can read more about this here: https://developers.google.com/earth-engine/guides/client_server

If you want necessarily to use if-statement, you can use EE version of it, but I would not recommend it (better use .evaluate() - first option in your script).

Here's a modified script: https://code.earthengine.google.com/f7f9b55125ca6dcfe46249be971d7dbd

Related Question