자바스크립트

구글맵 API 사용 테스트

양상추상츄 2021. 11. 14. 23:24

 

 

[JavaScript] 구글맵 사용법 및 간단 예제

Javascript로 구글 맵 API 를 불러오고 간단하게 활용하는 방법을 정리해봤습니다. API 사용설정, 구글맵 띄우기, 마커 표시, 지도 중심 변경 순서로 포스팅을 작성했습니다. 1. API 사용설정 Javascript에

popcorn16.tistory.com

헬로알파카님 블로그 참고하여 연습하였습니다.

 

구글 클라우드 플랫폼에서 구글맵 API키를 받아야 합니다.

 

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

구글 클라우드 플랫폼 -> 프로젝트 생성 -> maps javascript api 찾기 -> 사용자 인증 정보 생성 -> API키 복사

 

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Google Map</title>
</head>

<body>
<button type="button" id="button">지도 중심 이동하기</button>

<div id="map" style="width:100%; height: 100vh;"></div>

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=initMap&region=kr"></script>

<script src="./map.js"></script>
</body>
</html>

 

자바스크립트 파일

var map;

var button = document.getElementById('button');
button.addEventListener('click', changeCenter);

function initMap() {
    var seoul = { lat: 37.5642135 ,lng: 127.0016985 };
    map = new google.maps.Map( document.getElementById('map'), {
        zoom: 12,
        center: seoul
    });

    new google.maps.Marker({
        position: seoul,
        map: map,
        label: "서울 중심 좌표"
    });

}

function changeCenter(){
    var busan = { lat: 35.1379222, lng: 129.05562775 };
    map.panTo(busan);
    map.setZoom(14);

    new google.maps.Marker({
        position: busan,
        map: map,
        label: "부산 중심 좌표"
    })
}

 

'자바스크립트' 카테고리의 다른 글

자바스크립트 Event Target  (0) 2021.11.16
자바스크립트 버블링 / 캡처링  (0) 2021.11.16
자바스크립트 : 알아야 될 용어정리  (0) 2021.11.13
Undefined 이해하기  (0) 2021.11.11
홀짝 맞추기 프로그램  (0) 2021.11.08