Javascript – Google Maps zoomOut-Pan-zoomIn animation

google mapsjavascriptsettimeout

I'm wondering how I get a smooth zoom in animation with the Google Maps API.

I have 2 points, one in, let say China, and one in France. When I'm zoomed in on China, and click the button France. I want it to gradually zoom out smooth, one zoom level at the time. When it's zoomed out it should pan to the new location, and then zoom in on the new location one zoom level at the time.

How can I do this?

Best Answer

You need the zoomOut method with the continuous zoom parameter set to do the zoom and the panTo method to do the smooth panning to the new centerpoint.

You can listen to the zoomEnd and moveEnd events on the map object to chain together your zoomOut, panTo and zoomIn methods.


So in the course of implementing a sample for this problem, I discovered that the doContinuousZoom param on ZoomIn and ZoomOut (or just EnableContinuousZoom on the map) doesn't quite work as expected. It works ok when zooming out, if the tiles are in the cache (this is an important point, if the tiles aren't cached then it is not really possible to get the smooth animation you are after) then it does some nice scaling on the tiles to simulate a smooth zoom animation and introduces a ~500 ms delay on each zoom step so you can do it asynchronously (unlike panTo, which you will see in my example I use a setTimeout to call async).

Unfortunately the same is not true for the zoomIn method, which just jumps to the target zoom level without the scaling animation for each zoom level. I haven't tried explicitly setting the version for the google maps code, so this might be something that is fixed in later versions. Anyway, here is the sample code which is mostly just javascript hoop jumping and not so much with the Google Maps API:

Because this approach seems a bit unreliable, I think it would make more sense to do the async processing for setZoom explicitly (Same as the panning stuff).


So I do the async zooming explicitly now (using setTimeout with a single zoom at a time). I also have to fire events when each zoom happens so that my events chain correctly. It seems like the zoomEnd and panEnd events are being called synchronously.

Setting enableContinuousZoom on the map doesn't seem to work, so I guess calling zoomOut, zoomIn with the param is the only way to get that to work.