그럼에도 불구하고

👨‍💻

[TypeScript] TypeScript로 Google Maps API 사용하기 본문

TypeScript/TypeScript basics

[TypeScript] TypeScript로 Google Maps API 사용하기

zenghyun 2023. 5. 13. 20:42

오늘은 TypeScript로 Google Maps API 사용해 보겠습니다.

 

 

기능적인 측면에 목적을 두었기 때문에 외적인 모습은 딱히 꾸미지 않았습니다 :)

 

 

📌 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
<!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>Understanding TypeScript</title>
  <script src="dist/bundle.js" defer></script>
  <script 
    src="https://maps.googleapis.com/maps/api/js?key=발급받은 API KEY" async defer></script>
  <link rel="stylesheet" href="./src/app.css">
  
</head>
<body>
  <div id="map">
    <p>Please enter an address!</p>
  </div>
  <form>
    <input type="text" id="address">
    <button type="submit">SEARCH ADDRESS</button>
  </form>
</body>
</html>
cs

 

1
2
<script src="https://maps.googleapis.com/maps/api/js?key=발급받은 API KEY" async defer></script>
 
cs

 

발급받은 API KEY를 채워주시면 됩니다. 

 

https://developers.google.com/maps?hl=ko 

 

Google Maps Platform  |  Google Developers

Google Maps Platform 설명

developers.google.com

 

 

 

📌 app.ts

 

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
import axios from "axios";
 
const form = document.querySelector("form")!;
const address = document.getElementById("address")! as HTMLInputElement;
 
const GOOGLE_API_KEY = "발급받은 API KEY";
 
declare var google: any; 
 
type GoogleGeocodingResponse = {
  results: { geometry: { location: { lat: number; lug: number } } }[];
  status: "OK" | "ZERO_RESULTS";
};
 
const submitHandler = (event: Event) => {
  event.preventDefault();
  const inputAddressValue = address.value;
 
  axios
    .get<GoogleGeocodingResponse>(
      `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURI(
        inputAddressValue
      )}&key=${GOOGLE_API_KEY}`
    )
    .then((response) => {
      if (response.data.status !== "OK") {
        throw new Error("Could not find address");
      }
      const coordinates = response.data.results[0].geometry.location;
      const map = new google.maps.Map(document.getElementById("map"), {
        center: coordinates,
        zoom: 16
      }); 
 
      new google.maps.Marker({position: coordinates, map: map});
    })
    .catch((e) => {
      alert(e.message);
      console.log(e);
    });
};
 
form.addEventListener("submit", submitHandler);
 
cs

 

 

 

 

 

Comments