JavaScript | Google map API - Geolocation (현재 위치 표시)

파과·2022년 7월 1일

Google Map API

목록 보기
4/4

🔗Maps JavaScript API 가이드: Show current location

참고: Geolocation

This example creates a map that displays the geographic location of a user or device on a Google map, through use of their browser's HTML5 Geolocation feature.


현재 위치 표시하는 코드

let map = new google.maps.Map(document.getElementById('map'), {
  center: { lat: 37,  lng: 126 },
  zoom: 12
});

// 현재 위치 표시
if(navigator.geolocation){
  navigator.geolocation.getCurrentPosition(function(position){
    let pos = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    };
    map.setCenter(pos);
  }, function(){
    handleLocationError(false, infoWindow, map.getCenter());
  });
}else {
  handleLocationError(false, infoWindow, map.getCenter());
}

function handleLocationError(browerHasGeolocation, infoWindow, pos){
  infoWindow.setPosition(pos);
  infoWindow.setContent(browserHasGeolocation ?
                        '오류: 지오로케이션 연결 실패' :
                        '오류: 브라우저에서 지오로케이션을 지원하지 않음');
}
  • 코드 출처 - 자바스크립트 프로젝트북: 실무에 적합한 9가지 프로젝트로 배우는 웹 프로그래밍

🔗Geolocation Documentation

0개의 댓글