はじめに
Geolocationで位置情報を取得する実装をしている際、位置情報取得位置と違う位置に地図画面が遷移する症状が発生し、こちらの解決方法について記事にします。
【修正前のコードです】
.tsx
import { useAtom } from 'jotai';
import { latitudeAtom, longitudeAtom } from './Atom';
import { useNavigate } from 'react-router';
export const GeolocationFetch = () => {
const navigate = useNavigate();
const [latitude, setLatitude] = useAtom<number | null>(latitudeAtom);
const [longitude, setLongitude] = useAtom<number | null>(longitudeAtom);
const onClickFetchGeoLocation = () => {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
navigate('/mapPage');
}
const successCallback = (position: GeolocationPosition) => {
setLatitude(position.coords.latitude); // 緯度取得
setLongitude(position.coords.longitude); // 経度取得
};
const errorCallback = (error: GeolocationPositionError) => {
alert('位置情報を取得できませんでした');
};
return (
<>
<div
className='flex flex-col items-center justify-center'
>
<div
className='flex flex-col items-center'
>
<div className='text-xl font-bold'>GeolocationFetchページ</div>
<button
className='py-1 px-5 bg-sky-500 rounded-2xl font-black border text-white'
onClick={onClickFetchGeoLocation}
>位置情報を取得後画面遷移</button>
</div>
</div>
</>
)
}
解決方法
画面遷移するタイミングを位置情報を取得してからに変更
.tsx
import { useAtom } from 'jotai';
import { latitudeAtom, longitudeAtom } from './Atom';
import { useNavigate } from 'react-router';
export const GeolocationFetch = () => {
const navigate = useNavigate();
const [latitude, setLatitude] = useAtom<number | null>(latitudeAtom);
const [longitude, setLongitude] = useAtom<number | null>(longitudeAtom);
const onClickFetchGeoLocation = () => {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
}
const successCallback = (position: GeolocationPosition) => {
setLatitude(position.coords.latitude); // 緯度取得
setLongitude(position.coords.longitude); // 経度取得
navigate('/mapPage'); // ← ココ
};
const errorCallback = (error: GeolocationPositionError) => {
alert('位置情報を取得できませんでした');
};
return (
<>
<div
className='flex flex-col items-center justify-center'
>
<div
className='flex flex-col items-center'
>
<div className='text-xl font-bold'>GeolocationFetchページ</div>
<button
className='py-1 px-5 bg-sky-500 rounded-2xl font-black border text-white'
onClick={onClickFetchGeoLocation}
>位置情報を取得後画面遷移</button>
</div>
</div>
</>
)
}
参考
おわりに
解決できてよかったです。