I am trying to do a spatial join of two feature collections: points to watershed polygons. Many of the points are outside of the polygon area so I want to join the point to the nearest polygon. Ideally the output would be a table of points with the properties of the nearest watershed appended.

I have done a simple spatial join but my problems at the moment are:

  1. This outputs all the nearest polygons in the search area; and
  2. The output doesn't include the secondary feature collection properties in the output table.

How do I do this please?

Here is the code:

//var sg_fc: Table  //imported table of points

// Load the HydroATLAS dataset.
var basinATLAS = ee.FeatureCollection('WWF/HydroATLAS/v1/Basins/level12');

// Define a spatial filter, with distance 10 km.
var distFilter = ee.Filter.withinDistance({
  distance: 10000,
  leftField: '.geo',
  rightField: '.geo',
  maxError: 10

// Define a saveAll join.
var distSaveAll = ee.Join.saveAll({
  matchesKey: 'points',
  measureKey: 'distance',
  ordering: 'distance'

// Apply the join.
var spatialJoined = distSaveAll.apply(basinATLAS,sg_fc,distFilter);

Map.addLayer(spatialJoined, {}, 'spatial join');
Map.addLayer(sg_fc, {}, 'sites')


Link to code editor: https://code.earthengine.google.com/90243d26764b46441efc1b477db185cf

1 Answer 1

  1. Don't use saveAll(), use saveBest().
  2. You can't output nested features; only primitive objects (numbers, strings, geometries). You'll have to copy the parts of the saved feature you want (name, ID, whatever) into the primary feature.
  • Thanks for these suggestions. 1. I've changed to saveFirst() join to get the hydrobasins closest to the point. 2. Regarding your second point, how would I do this please? I want to copy all the secondary features properties into the primary feature to export.
    – splodyn
    Commented Jun 30, 2023 at 14:14

Your Answer

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

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