Google Earth Engine Union – How to Get Union of Multiple Polygons in GEE

google-earth-enginemulti-polygonpolygonunion

I would like to get the union of m (m is variable) different (multi)polygons in Google Earth Engine. The attribute .union() only works with two polygons. See example below for what I have till now.

var ADM2 = ee.FeatureCollection("FAO/GAUL/2015/level2");
var filter1 = ee.Filter.inList('ADM2_NAME', ['Bukidnon']);
var Bukidnon = ADM2.filter(filter1);
var geoBukidnon=Bukidnon.geometry();
Map.centerObject(geoBukidnon)
Map.addLayer(geoBukidnon, {}, 'Bukidnon')

var filter2 = ee.Filter.inList('ADM2_NAME', ['Misamis Oriental']);
var MisamisOriental = ADM2.filter(filter2);
var geoMisamisOriental=MisamisOriental.geometry();
Map.addLayer(geoMisamisOriental, {}, 'Misamis Oriental')

var filter3 = ee.Filter.inList('ADM2_NAME', ['Davao del Norte']);
var DavaodelNorte = ADM2.filter(filter3);
var geoDavaodelNorte=DavaodelNorte.geometry();
Map.addLayer(geoDavaodelNorte, {}, 'Davao del Norte')

// I want the union of geoBukidnon, geoMisamisOriental and geoDavaodelNorte
// but .union() only works with two geometries (see below), whereas I want to get the union 
// of m different (multi)polygons (in this case, m = 3)

var union = geoBukidnon.union(geoMisamisOriental)
Map.addLayer(union, {}, 'union')

var union2 = union.union(geoDavaodelNorte)
Map.addLayer(union2, {}, 'union2')

So I want to get the result of union2 in one step without having to write m-1 lines of code that apply the attribute .union().

Best Answer

You can merge geometries from all features in your feature collection into one multiPolygon and than use a .dissolve() function.

var filterAll = ee.Filter.inList('ADM2_NAME', 
['Misamis Oriental', 'Davao del Norte', 'Bukidnon']);
var all = ee.FeatureCollection(ADM2.filter(filterAll)).geometry().dissolve()

Link to the code: https://code.earthengine.google.com/d3874a00d59a226671a201d4d7ab713e