그럼에도 불구하고

👨‍💻

Google maps platform API 사용하기 본문

JavaScript/Function implementation

Google maps platform API 사용하기

zenghyun 2023. 4. 14. 17:07

 

Google maps platform API 사용하여 내 위치 찾기, 위치 검색, 위치 공유 할 수 있는 페이지를 만들어보겠습니다. 

 

 

 

Google Maps Platform 문서  |  Google Developers

Google Maps Platform 문서

developers.google.com

 

 

API Key  발급받기: https://developers.google.com/maps/gmp-get-started?hl=ko

 

 

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Share a Place</title>
    <link rel="stylesheet" href="./styles/app.css" />
    <link rel="stylesheet" href="./styles/share-place.css" />
    <script 
    src="https://maps.googleapis.com/maps/api/js?key=<API 키>"
    async defer>
</script>
    <script src="./SharePlace.js" type="module" defer></script>
  </head>
  <body>
    <template id="modal-template">
      <div class="backdrop"></div>
      <div class="modal"></div>
    </template>
    <template id="loading-modal-content">
      <div class="modal__content centered">
        <div class="lds-dual-ring"></div>
      </div>
    </template>
 
    <header>
      <h1>Share a Place!</h1>
    </header>
 
    <section id="selected-place">
      <div id="map">
        <p>
          <mark>내 위치 얻기</mark> 버튼을 클릭해보세요!
        </p>
      </div>
    </section>
 
    <section id="share-controls">
      <input
        id="share-link"
        type="text"
        readonly
        value="Select a place to get a sharable location."
      />
      <button id="share-btn" disabled>주소 공유</button>
    </section>
 
    <section id="place-data">
      <form>
        <label for="address">주소</label>
        <input type="text" />
        <button type="submit">위치 찾기</button>
      </form>
      <button id="locate-btn">내 위치 얻기</button>
    </section>
  </body>
</html>
 
cs

 

 

구글  Maps API 스크립트 불러오기

원격에 있는 구글 서버로부터 Google Maps API의 코드를 내려받기 위함입니다.

 

<API 키>에는 내가 발급받은 고유 API 키를 넣어주시면 됩니다.

 

1
2
<script src="https://maps.googleapis.com/maps/api/js?key=<API 키>" async defer> </script>
  
cs

 

SharePlace.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import { Modal } from "./UI/Modal.mjs";
import { Map } from "./UI/Map.mjs";
import {
  getCoordsFromAddress,
  getAddressFromCoords,
from "./Utility/Location.mjs";
 
class PlaceFinder {
  constructor() {
    const addressForm = document.querySelector("form");
    const locateUserBtn = document.getElementById("locate-btn");
    this.shareBtn = document.getElementById("share-btn");
 
    locateUserBtn.addEventListener("click"this.locateUserHandler.bind(this));
    this.shareBtn.addEventListener("click"this.sharePlaceHandler);
    addressForm.addEventListener("submit"this.findAddressHandler.bind(this));
  }
 
  sharePlaceHandler() {
    const sharedLinkInputElement = document.getElementById("share-link");
    if (!navigator.clipboard) {
      sharedLinkInputElement.select();
      return;
    }
    navigator.clipboard
      .writeText(sharedLinkInputElement.value)
      .then(() => {
        alert("Copied into clipboard!");
      })
      .catch((err) => {
        console.log(err);
        sharedLinkInputElement.select();
      });
  }
 
  selectPlace(coordinates, address) {
    if (this.map) {
      this.map.render(coordinates);
    } else {
      this.map = new Map(coordinates);
    }
    this.shareBtn.disabled = false;
    const sharedLinkInputElement = document.getElementById("share-link");
    sharedLinkInputElement.value = address;
  }
 
  locateUserHandler() {
    if (!navigator.geolocation) {
      alert(
        "Location Feature is not available in your browser - please use a more modern browser"
      );
      return;
    }
    const modal = new Modal(
      "loading-modal-content",
      "Loading location = please wait"
    );
    modal.show();
    navigator.geolocation.getCurrentPosition(
      async (successResult) => {
        const coordinates = {
          lat: successResult.coords.latitude,
          lng: successResult.coords.longitude,
        };
        const address = await getAddressFromCoords(coordinates);
        modal.hide();
        this.selectPlace(coordinates, address);
      },
      (error) => {
        modal.hide();
        alert(
          "Could not locate your unfortunately. Please enter an address manually!"
        );
      }
    );
  }
 
  async findAddressHandler(event) {
    event.preventDefault();
    const address = event.target.querySelector("input").value;
    if (!address || address.trim().length === 0) {
      alert("Invalid address entered - please try again!");
      return;
    }
    const modal = new Modal(
      "loading-modal-content",
      "Loading find location = please wait"
    );
    modal.show();
    try {
      const coordinates = await getCoordsFromAddress(address);
      this.selectPlace(coordinates, address);
    } catch (err) {
      alert(err.message);
    }
    modal.hide();
  }
}
 
const placeFinder = new PlaceFinder();
 
cs

 

Map.mjs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
export class Map {
  constructor(coords) {
    this.render(coords);
  }
 
  render(coordinates) {
    if (!google) {
      alert("Could not load maps library - please try agin later!");
    }
    const map = new google.maps.Map(document.getElementById("map"), {
      center: coordinates,
      zoom: 16,
    });
 
    new google.maps.Marker({
      position: coordinates,
      map: map,
    });
  }
}
 
cs

 

Modal.mjs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
export class Modal {
    constructor(contentId, fallbackText) {
        this.fallbackText = fallbackText;
        this.contentTemplateEl = document.getElementById(contentId);
        this.modalTemplateEl = document.getElementById('modal-template');   
    }
 
    show() {
        if('content' in document.createElement('template')) {
            const modalElements = document.importNode(this.modalTemplateEl.contenttrue);
            this.modalElement = modalElements.querySelector('.modal');
            this.backdropElement = modalElements.querySelector('.backdrop');
            const contentElement = document.importNode(this.contentTemplateEl.contenttrue);
 
            this.modalElement.appendChild(contentElement);
 
            document.body.insertAdjacentElement('afterbegin'this.modalElement);
            document.body.insertAdjacentElement('afterbegin'this.backdropElement);
        } else {
            alert(this.fallbackText);
        }
    }
 
    hide() {
        if(this.modalElement) {
            document.body.removeChild(this.modalElement);
            document.body.removeChild(this.backdropElement);
            this.modalElement = null;
            this.backdropElement = null
        }
    }
}
cs

 

 

Location.mjs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const GOOGLE_API_KEY = '';
 
export async function getAddressFromCoords(coords) {
   const response = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${coords.lat},${coords.lng}&key=${GOOGLE_API_KEY}`)
   if(!response.ok){
      throw new Error('Failed to fetch address. Please try again!');
   }
   const data = await response.json();
   if(data.error_message) {
      throw new Error(data.error_message);
   }
   const address = data.results[0].formatted_address;
   return address;
}
 
export async function getCoordsFromAddress(address) {
 const urlAddress = encodeURI(address);
 const response = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${urlAddress}&key=${GOOGLE_API_KEY}`);
 if(!response.ok){
    throw new Error('Failed to fetch coordinates. Please try again!');
 }
 const data = await response.json();
 if(data.error_message) {
    throw new Error(data.error_message);
 }
 console.log(data);
 const coordinates = data.results[0].geometry.location;
 return coordinates;
}
cs

 

const GOOGLE_API_KEY = '';

 

발급받은 API 키를 넣어주시면 됩니다. 

 

 

 

실제 화면

 

내 위치 얻기 클릭 시 로드된 화면 ( 제 위치를 올리기 그래서 줌을 최소화하였습니다..^^)

 

 

 

위치 찾기 버튼 클릭 시 (서울역 검색) 

 

주소 공유 클릭

 

여기서 ctrl+c / cmd+c를 눌렀을 때 => 서울역

'JavaScript > Function implementation' 카테고리의 다른 글

카메라 기능 사용하기  (0) 2023.03.23
이미지 로딩 지연시키기  (0) 2023.03.22
배경색 무작위 조작하기  (0) 2023.02.02
숫자 뽑기 게임  (0) 2023.01.31
Drag & Drop 이용하여 이미지 올리기  (0) 2023.01.26
Comments