Geolocation API는 웹에서 사용자의 위치 정보를 알 수 있는 API로 크게 현재 위치 가져오기와 실시간으로 위치 추적하기 기능이 있다.
아래는 공식문서 링크이다.
예제
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
},
(error) => {
console.error("Error getting location:", error);
}
);
} else {
console.log("Geolocation API not supported by this browser.");
}
예제
let watchId;
if (navigator.geolocation) {
watchId = navigator.geolocation.watchPosition(
(position) => {
console.log("New position:", position.coords.latitude, position.coords.longitude);
},
(error) => {
console.error("Error watching location:", error);
}
);
} else {
console.log("Geolocation API not supported by this browser.");
}
// 위치 추적 중단
function stopWatchingLocation() {
if (watchId) {
navigator.geolocation.clearWatch(watchId);
}
}
당연하지만 이 API는 HTTPs에서 사용하도록 권장한다.
현재 내가 진행중인 프로젝트에서 구글맵스를 사용해야 하는데 Geolocation API를 통해 가져온 위도와 경도를 활용하면 좋을 것 같다.
