Geolocation API는 GPS를 비롯한 ,WI-FI , 휴대전화의 기지국, IP 주소 등에서 위치 정보를 알아낸다.
메서드
navigator.geolocation.getCurrentPosition();
// 사용자의 현재 위치를 요청
navigator.geolocation.watchPosition();
// 현재 위치를 요청하는 것은 동일하지만,
// 지속적으로 확인하여 사용자의 위치가 변경될 때마다 지정된 콜백함수를 호출 (clearWatch()로 꺼줘야함)
navigator.geolocation.clearWatch();
// 사용자의 위치 정보를 수집하는 작업을 중단
// 메서드의 전달인자는 watchPosition()을 호출한 다음 반환받은 숫자 값이어야 한다.
Geolocation API는 비동기적으로 동작하는데, getCurrentPosition() 과 watchPosition()은 즉시 반환하지만, 사용자의 위치가 결정되거나 변경될 때마다 실행시킬 콜백 함수를 인자로 받는다.
const watchID = navigator.geolocation.watchPosition((position) => {
console.log(position.coords.latitude, position.coords.longitude);
});
// 위치가 변할 때마다 일정 주기로 watchPosition안의 콜백함수가 호출된다.
// 노트북이나 핸드폰의 배터리를 많이 소모하기 때문에
// clearWatch로 해제해줘야한다.
navigator.geolocation.clearWatch(watchID);
// 위의 watchID 호출을 해제
navigator.geolocation.getCurrentPosition(function(pos) {
let latitude = pos.coords.latitude;
let longitude = pos.coords.longitude;
alert("현재 위치 : " + latitude + ", "+ longitude);
});