How to pan and zoom animated? #581
Replies: 2 comments 4 replies
-
One thing you could try is using the Note: "Calling this method may cause a smooth animation as the map pans and zooms to fit the bounds. Whether or not this method animates depends on an internal heuristic" So, there is no guaranty that will be an animation, but my guess would be that the api uses similar heuristics as when calling I know its not quite the same and requires some rethinking of your mechanism to "zoom to a marker on click" |
Beta Was this translation helpful? Give feedback.
-
Below is a very basic implementation of such an animation using a custom hook. Notes about this implementation:
You can, of course, do a lot more with this basic technique, for example, use a library like GSAP or tween.js to do the interpolation instead of the simple geometric series approach here. function useMapAnimation() {
const map = useMap();
const flyTo = useCallback(
(toLatLng: google.maps.LatLngLiteral, toZoom: number) => {
if (!map) return;
requestAnimationFrame(function loop() {
const {lat, lng} = map.getCenter()?.toJSON() || {lat: 0, lng: 0};
const zoom = map.getZoom() || 0;
// finish animation by setting final values
if (
Math.abs(toLatLng.lat - lat) < 0.000001 &&
Math.abs(toLatLng.lng - lng) < 0.000001 &&
Math.abs(toZoom - zoom) < 0.01
) {
map.moveCamera({center: toLatLng, zoom: toZoom});
return;
}
// schedule another animation frame
requestAnimationFrame(loop);
// move a certain percentage closer to destination with every frame, this both
// controls the overall timing and adds a nice exponential easing
map.moveCamera({
center: {
lat: lat + (toLatLng.lat - lat) * 0.1,
lng: lng + (toLatLng.lng - lng) * 0.1
},
zoom: zoom + (toZoom - zoom) * 0.04
});
});
},
[map]
);
return {flyTo};
}
// usage example:
const MyMap = () => {
const {flyTo} = useMapAnimation();
const handleMapClick = useCallback(() => {
flyTo({lat: 53.55, lng: 10.05}, 10);
}, [flyTo]);
return (
<Map
{...mapProps}
onClick={handleMapClick}
/>
);
}; |
Beta Was this translation helpful? Give feedback.
-
Hi! I want to pan and zoom on a marker when clicked but with an animation.
If I pan to latLng it will animate but not when I use zoom.
If I call
map.setZoom()
immidiatelly aftermap.panTo()
it will override the animation and just zooms straight to the point.Example component
Beta Was this translation helpful? Give feedback.
All reactions