Google Earth Engine – Setting Coordinates of Map Center from FeatureCollection Geometry

google-earth-engine

I would like to set the coordinates of the map centre using the coordinates from a geometry.

// randomly select 100 points
points = points.randomColumn('random');
var P = ee.Number(100).divide(points.size());
points = points.filter(ee.Filter.lt('random', P));
print (points)

// plot them
Map.addLayer(points);
var centre = points.geometry().centroid().coordinates();
print (ee.Number(centre.get(0)), ee.Number(centre.get(1)));
Map.setCenter(ee.Number(centre.get(0)), ee.Number(centre.get(1)), 9);
// Map.setCenter(-0.06657026751372405, 51.47080255078299, 9);

I am getting the error

Provided center object has invalid values for lat, lon, or zoom.
Expected numeric values.

Link to example

Best Answer

As described here any class which does not start with ee.Thing, usually needs client side inputs. Therefore, the Map.setCentre() needs two/three client side numbers. To make your code easily working, use getInfo():

Map.setCenter(ee.Number(centre.coordinates().get(0)).getInfo(), 
              ee.Number(centre.coordinates().get(1)).getInfo(), 9);

Or use evaluate on longer running results: link

Although I would recommend to use another, similar function: centerObject(). That automatically centers the map to the center of a geometry, feature or feature collection and you don't need a getInfo call:

Map.centerObject(points, 9);
Related Question