안녕하세요.
아래 예제 코드와 같이 Javascript Geolocation 기능을 사용하여 사용자의 실시간 위치 정보를 조회하여 카카오 지도를 다시 띄워주려고 합니다.(참고 자료: https://7942yongdae.tistory.com/150)
다만, 카카오 지도 Javascript API에서 제공(Web 방식)하는 new kakao.maps.Map() 코드를 사용해서 Map 객체를 계속해서 만들어내는 것이 추후 사이트 성능에 문제가 되지 않을까 생각이 드는데요.
Map 객체를 다시 만들지 않고도, 지도를 Reload(?) 시켜주는 방법이 있을까요?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Javascript Geolocation을 사용한 실시간 사용자의 위치 확인 방법</h1>
<h3 id="userLocation"></h3>
<div id="map" style="width: 500px; height: 400px"></div>
<script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=발급받은 APP KEY를 넣으시면 됩니다.&libraries=services,clusterer,drawing"></script>
<script>
if (navigator.geolocation) {
navigator.geolocation.watchPosition(success); // watchPosition()는 사용자의 위치에 변화가 발생하면 호출됩니다.
}
function success({ coords, timestamp }) {
const latitude = coords.latitude; // 위도
const longitude = coords.longitude; // 경도
console.log(`위도: ${latitude}, 경도: ${longitude}, 위치 반환 시간: ${timestamp}`);
document.getElementById(
'userLocation'
).innerText = `위도: ${latitude}, 경도: ${longitude}, 위치 반환 시간: ${timestamp}`;
const container = document.getElementById('map');
const options = {
center: new kakao.maps.LatLng(latitude, longitude), // 지도의 중심좌표(위도, 경도)
level: 3, //지도의 레벨(확대, 축소 정도)
};
const map = new kakao.maps.Map(container, options); // 지도 생성 및 객체 리턴
}
</script>
</body>
</html>