8.0 Geolocation

gangmin·2021년 12월 26일
0

강의

이번 날씨편에서는 예전에 전혀 사용해본적 없는 함수를 써볼거다.

이 함수는 유저의 위치(Geolocation)를 준다.

getCurrentPosition(successCallback, errorCallback)

  • success함수는 GeolocationPosition object 하나를 입력받는다. 그 말은 JS가 GeolocationPosition object를 줄거다.
function onGeoOk(position){
    console.log(position)
}
function onGeoError(){
    alert("Can't find you. No weather for you.")
}
navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

새로고침을 하고 "이 파일에서 다음 권한을 요청합니다. :내 위치 확인 = 허용/차단" 이 뜬다. 허용을 누르면 콘솔에 GeolocationPosition {coords: GeolocationCoordinates, timestamp: 1640534750466} 와 coords(좌표) 정보가 나온다.

latitude: 35.2211402 / longitude: 129.0814828 위도와 경도의 정보가 나온다!!

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    console.log("You live it",lat,lng);
}
>> You live it 35.2211402 129.0814828

이렇게 하면 위치를 알 수 있다!! 굉장히 간단하지 않은가?!


이 숫자들을 장소로 바꿔줄 서비스를 사용해야한다. 좌표만 보고 바로 어느 나라고 도시인지 알 수는 없으니까ㅇㅇ 일단 API계정을 열어야 한다. 여기로 이동

위 사이트는 우리가 있는 장소의 이름과 날씨를 알려줄거다. 근데 이건 다음 영상에서 할거다.

결론

우리는 이 모든걸 10줄로 끝을 냈다. 20년전만 해도 상상을 못했을법한...굉장히 대단하지 않은가?!

완성된 코드

function onGeoOk(position){
    const lat = position.coords.latitude;
    const lng = position.coords.longitude;
    console.log("You live it",lat,lng);
}
function onGeoError(){
    alert("Can't find you. No weather for you.")
}
navigator.geolocation.getCurrentPosition(onGeoOk,onGeoError);

0개의 댓글