Skip to content

Commit

Permalink
feat: add useZoom hook
Browse files Browse the repository at this point in the history
  • Loading branch information
hwbllmnn committed Sep 6, 2023
1 parent acbce18 commit c8eefcd
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/hooks/useZoom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { AnimationOptions as OlViewAnimationOptions } from 'ol/View';
import {
useEffect
} from 'react';

import useMap from './useMap';

/**
* This hook adds an interaction to the map and removes/updates it if the dependency array changes.
* It accepts an optional active parameter that toggles the active state of the interaction. If it is undefined the
* active state will not get changed.
* @param constructor returns an interaction to be added to the map, will be called again, if the interaction needs
* to be updated
* @param active
*/
export const useZoom = (
/**
* Whether the zoom in shall be animated.
*/
animate: boolean,
/**
* The delta to zoom when clicked. Defaults to positive `1` essentially zooming-in.
* Pass negative numbers to zoom out.
*/
zoom: number,
/**
* The options for the zoom animation. By default zooming will take 250
* milliseconds and an easing which starts fast and then slows down will be
* used.
*/
animateOptions?: OlViewAnimationOptions
) => {
const map = useMap();

useEffect(() => {
if (!map) {
return undefined;
}
const view = map.getView();
if (!view) { // no view, no zooming
return undefined;
}
if (view.getAnimating()) {
view.cancelAnimations();
}

if (animate && animateOptions) {
const {
duration,
easing
} = animateOptions;
const finalOptions = {
zoom,
duration,
easing
};
view.animate(finalOptions);
} else {
view.setZoom(zoom);
}
}, [map, zoom, animate, animateOptions]);
};

export default useZoom;

0 comments on commit c8eefcd

Please sign in to comment.