어제 navigator.geolocation.getCurrentPosition() 을 통해 내가 위치한 곳의 좌표(위도, 경도)를 가져올 수 있었다.
navigator.geolocation.getCurrentPosition(function (position) {
setLat(position.coords.latitude); //위도
setLong(position.coords.longitude); //경도
});
현 위치의 날씨를 구해야해서 openweathermap의 api를 사용했다.
어제까지만 해도 도시 이름을 가지고 날씨를 구했었는데,
const url = `http://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid=${apiKey}`;
위도, 경도로 날씨를 구하는 것으로 바꿨다.
const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${apiKey}`;
여기서, 가져오는 위치가 영어로 표시된다는 점과 위치가 정확하지 않다는 점에서 카카오 api를 사용하기로 했다.
일전에 리액트로 개발할 때 카카오맵 api를 사용한 경험이 있었는데, 이땐 index.html에 카카오에서 제공하는 스크립트 코드를 넣어줘야 했는데 next엔 index파일이 따로 없어서 어떻게 해야하나 찾아보다가
next 환경에서는 _document.js에서 커스텀을 해주면 된다는 것을 알게됐다.
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { secret } from '../secret';
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
const kakaoKey = secret.kakaokey;
return (
<Html>
<Head>
<script
type='text/javascript'
src={`//dapi.kakao.com/v2/maps/sdk.js?appkey=${kakaoKey}&libraries=services`}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
해당 링크에서 가져온 기본 틀에서
보안이 필요한 api 코드와 카카오맵 script만 추가해줬다.
이렇게하면 next 환경에서 카카오맵 api가 사용이 가능해진다.
const getAddr = (lat, long) => {
let geocoder = new kakao.maps.services.Geocoder();
let coord = new kakao.maps.LatLng(lat, long);
let callback = function (result, status) {
if (status === kakao.maps.services.Status.OK) {
// 지역이름 설정, 시~구까지만 출력
setCityName(result[0].address.region_2depth_name);
}
};
geocoder.coord2Address(coord.getLng(), coord.getLat(), callback);
};
if (typeof window !== 'undefined') {
navigator.geolocation.getCurrentPosition(function (position) {
setLat(position.coords.latitude);
setLong(position.coords.longitude);
getAddr(lat, long);
});
}
카카오로 '전주시 덕진구'를 출력, openweathermap를 통해 날씨와 기온, 습도를 출력했다.