1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

react-google-maps/apiでonDragEndやonZoomChangedを使用するとマップの動きが変になる問題の解決法

Posted at

問題

React上で@react-google-maps/apiを使用して地図を表示させています。

その際マップの中心地、ズームの状態をjotaiへ保存するために、それぞれonDragEndonZoomChangedを使用していました。
そうすると、状態は確かに保存できているのですが、タッチデバイスでマップを操作した際すごく違和感のある挙動になってしまいました😢

それをうまいこと解決できたので、書いておこうと思います。

今回の解決方法は、保存するタイミングがコンポーネントのアンマウント時に限られています。
それ以外のタイミングで保存したい時は役に立たないかもしれません🙇🏻‍♂️

解決方法

react-useuseUnmountを使用してマップの中心地、ズームの状態を保存します。
react-useは便利なhooksを提供してくれるパッケージです。

react-useをプロジェクトに追加します。

npm i react-use

useUnMountをimportします。

import useUnmount from "react-use/lib/useUnmount";

アンマウント時に発火する関数を作成し、useUnMountに組み込みます。

const mapRef = useRef<google.maps.Map | null>(null);

const handleMapLoad = (map: google.maps.Map) => {
    mapRef.current = map;
};

const handleBeforeUnload = useCallback(() => {
    // refがnullの時は処理を飛ばす
    if (!mapRef.current) return;

    // refからzoom、centerの値を取得
    const newZoom = mapRef.current.getZoom();
    const newCenter = mapRef.current.getCenter()?.toJSON();

    // それぞれ
    if (newZoom) {
        // zoomを保存するコード
    }
    
    if (newCenter) {
        // centerの値を保存するコード
    }
}, []);

useUnmount(() => {
    handleBeforeUnload();
});

// ~~~~~~~~~~~~~~~~~~~ 省略 ~~~~~~~~~~~~~~~~~~~~~

<GoogleMap
    // ~~~~~ 省略 ~~~~~
    onLoad={handleMapLoad}
>

おわりに

お読みいただきありがとうございました!

参考サイト等

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?