camera.flyto -- preserve z value

I'm trying to do a camera flyto but not change the z value. If I have a hard-coded z value, like this, I'm fine.

viewer.camera.flyTo({
          destination : Cesium.Cartesian3.fromDegrees( longitude, latitude, 10e6)
});

But what if I don't know what the current z value is, what do I use? I've tried viewer.camera.position.z, but the camera always zooms in noticeably if use that.

Thanks for posting your question and solution! I’m sure others in the community will find this thread helpful.

The flyTo does take a “maximumHeight” option, but if you want to just keep it at the height it currently is, setting the current camera height to the destination height is a good way to do this. So you could do:

// Get the camera height
var cameraHeight = camera.positionCartographic.height;
// Here position is a Cartesian3 of the camera destination

var cartographicDesination = Cesium.Cartographic.fromCartesian(position);

// Override its height
cartographicDesination.height = cameraHeight;
// Set it back to a Cartesian3, then fly to this destination

position = Cesium.Cartographic.toCartesian(cartographicDesination);

``

I’ve modified the 3D Tiles Interactivity Sandcastle to do this, here’s a link. If you select “Zoom to feature” and then right click anywhere, the camera will move to that building without changing its height.

I'm trying to do a camera flyto but not change the z value. If I have a hard-coded z value, like this, I'm fine.

viewer.camera.flyTo({
          destination : Cesium.Cartesian3.fromDegrees( longitude, latitude, 10e6)
});

But what if I don't know what the current z value is, what do I use? I've tried viewer.camera.position.z, but the camera always zooms in noticeably if use that.

--------

Firgured out the answer right before I posted this, so here it is for anyone else who needs to do this:

Use viewer.camera._positionCartographic.height for the z-value of the destination and you will preserve the z-value when you fly to the destination. I have not tested this extensively, so I don't know if this works when you change your orientation. My camera is looking straight down and the orientation is remaining constant.

It’s more obvious what this does in the original example:

https://cesiumjs.org/Cesium/Build/Apps/Sandcastle/?src=3D%20Tiles%20Interactivity.html

If you comment it out, you can see the camera will zoom right through the building, instead of stop a little before.

That’s a good catch with that little hop. This happens because flyTo tries to maintain a minimum distance to the ground. Setting the maximumHeight to the destination height should remove that.