google-earth-engine – Using Variables with Map.setCenter in Google Earth Engine

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

How can I pass a variable to Map.setCenter? I'm trying to use GEE to to view a location that comes from a variable. That is, the following works:

var scene = "LC80122482013122LGN01"
var compare = ee.String('LANDSAT_SCENE_ID == "').cat(scene).cat('"')
var im = ee.ImageCollection.load('LANDSAT/LC8_L1T_TOA').filter(ee.Filter.expression(compare))
var IM = ee.Image(im.first());
Map.setCenter(-27.4713134765625, 81.4474921754631, 10)
Map.addLayer(IM);

But if I try to center based on variables that come from a string, I get an error message. For example, by adding

var lon = ee.Number.parse(ee.String("-27.4713134765625"));
Map.setCenter(lon, 81.4474921754631, 10)

So the full example is:

var scene = "LC80122482013122LGN01"
var compare = ee.String('LANDSAT_SCENE_ID == "').cat(scene).cat('"')
var im = ee.ImageCollection.load('LANDSAT/LC8_L1T_TOA').filter(ee.Filter.expression(compare))
var IM = ee.Image(im.first());
var lon = ee.Number.parse(ee.String("-27.4713134765625"));
Map.setCenter(lon, 81.4474921754631, 10)
Map.addLayer(IM);

I get the error message

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

Best Answer

The problem is that Map.setCenter is expecting number-objects on the client side as arguments, and in your example lon is actually a number-object on the server side. Thus, an easy way to transform a server side object to a client side one is using getInfo(). Here's the only change you need to make to your code. If you want to read more about server vs client side objects I suggest taking a look to the following link: https://developers.google.com/earth-engine/guides/client_server

Map.setCenter(lon.getInfo(), 81.4474921754631, 10)