Geolocation
공식 예제 대응네이버 공식 예제 보기 ↗
브라우저 Geolocation API로 현재 위치를 가져와 지도에 표시합니다.
코드 접기코드 보기
import { useEffect, useRef, useState } from 'react';
import {
NavermapsProvider,
Container as MapDiv,
NaverMap,
InfoWindow,
useNavermaps,
} from 'react-naver-maps';
const FALLBACK_CENTER = { lat: 37.5666805, lng: 126.9784147 };
type LocationState =
| { status: 'pending' }
| { status: 'success'; lat: number; lng: number }
| {
status: 'error';
reason: 'failed' | 'unsupported';
lat: number;
lng: number;
};
function GeolocationMapContent() {
const navermaps = useNavermaps();
const mapRef = useRef<naver.maps.Map>(null);
const [location, setLocation] = useState<LocationState>({
status: 'pending',
});
useEffect(() => {
if (!navigator.geolocation) {
setLocation({
status: 'error',
reason: 'unsupported',
...FALLBACK_CENTER,
});
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
setLocation({ status: 'success', lat: latitude, lng: longitude });
mapRef.current?.setCenter(new navermaps.LatLng(latitude, longitude));
mapRef.current?.setZoom(10);
},
() => {
const center = mapRef.current?.getCenter();
setLocation({
status: 'error',
reason: 'failed',
lat: center?.y ?? FALLBACK_CENTER.lat,
lng: center?.x ?? FALLBACK_CENTER.lng,
});
},
);
}, [navermaps]);
const renderContent = () => {
if (location.status === 'success') {
return `<div style="padding:20px;">geolocation.getCurrentPosition() 위치</div>`;
}
if (location.status === 'error') {
return (
`<div style="padding:20px;">` +
`<h5 style="margin-bottom:5px;color:#f00;">${location.reason === 'unsupported' ? 'Geolocation not supported' : 'Geolocation failed!'}</h5>` +
`latitude: ${location.lat}<br />longitude: ${location.lng}` +
`</div>`
);
}
return '';
};
return (
<NaverMap ref={mapRef} defaultCenter={FALLBACK_CENTER} defaultZoom={10}>
{location.status !== 'pending' && (
<InfoWindow
open
position={{ lat: location.lat, lng: location.lng }}
content={renderContent()}
/>
)}
</NaverMap>
);
}
function GeolocationMap() {
return (
<MapDiv style={{ width: '100%', height: '600px' }}>
<GeolocationMapContent />
</MapDiv>
);
}
export default function MapGeolocationExample() {
return (
<NavermapsProvider ncpKeyId="aluya4ff04">
<GeolocationMap />
</NavermapsProvider>
);
}설명
navigator.geolocation.getCurrentPosition()으로 현재 위치를 가져온 뒤 ref로 받은 지도의 setCenter()를 호출합니다. 실패하면 지도의 현재 중심에 실패 내용을 표시합니다. InfoWindow의 content는 HTML 문자열입니다.
React로 옮기며 바꾼 점
| 네이버 공식 예제 | 이 예제 |
|---|---|
new naver.maps.InfoWindow()에 setContent(), open(map, position) 호출 | 위치를 얻은 뒤 <InfoWindow open position content> 렌더링 |
| 성공·실패 콜백에서 정보 창을 직접 변경 | 콜백에서 location state(pending, success, error)를 변경하고 state에 따라 정보 창 표시 |
$(window).on('load')에서 위치 요청 | useEffect에서 요청 |