11

I would like to initialize cesium so that the map is centered on some specific coordinates instead of the default ones. I have the following initialization code:

var map = new Cesium.CesiumWidget('map-js');
map.centralBody.terrainProvider = new Cesium.CesiumTerrainProvider({
    url : 'http://cesiumjs.org/smallterrain'
});

Usually, with other mapping libraries, I would set the center on initialization, eg on mapbox:

map = L.mapbox.map('map-js', 'api-key').setView([42.12, 12.45], 9);

How to do that with cesium?

nemesisdesign
  • 8,159
  • 12
  • 58
  • 97

2 Answers2

7

Try adding this after your first block of code above:

var scene = map.scene;
var ellipsoid = Cesium.Ellipsoid.WGS84;
var west = Cesium.Math.toRadians(-77.0);
var south = Cesium.Math.toRadians(38.0);
var east = Cesium.Math.toRadians(-72.0);
var north = Cesium.Math.toRadians(42.0);

var extent = new Cesium.Rectangle(west, south, east, north);
scene.camera.viewRectangle(extent, ellipsoid);

More examples are available in our Camera Demo.

EDIT (May 2014): Due to Cesium API changes, .getCamera() is renamed .camera, the camera's .controller was removed and rolled into the camera itself, and Extent is renamed to Rectangle. The above code now reflects the new API. For a complete list of breaking changes, see CHANGES.md.

emackey
  • 11,818
  • 2
  • 38
  • 58
  • how can I convert a lat/long coordinate into an extent? I'm puzzled – nemesisdesign Feb 12 '14 at 12:40
  • If you have a single lat/lon pair, instead of 4 corners, just create the corners by adding or subtracting an offset from your point. The larger the offset, the more "zoomed out" the camera will be. – emackey Feb 12 '14 at 18:10
  • what about: flight = Cesium.CameraFlightPath.createAnimationCartographic(map.scene, { destination : Cesium.Cartographic.fromDegrees(coords.lng, coords.lat, coords.zoom), duration: 0 }); – nemesisdesign Feb 12 '14 at 18:48
7

If you want to keep the current "zoom" (aka camera distance from ellipsoid) and only have lon/lat, you could call setView() and use the current camera height, like:

    viewer.camera.setView({
        destination : Cesium.Cartesian3.fromDegrees(
            longitude,
            latitude,
            Cesium.Ellipsoid.WGS84.cartesianToCartographic(viewer.camera.position).height
        )
    });
danwild
  • 1,886
  • 1
  • 26
  • 31