본문 바로가기
TYPESCRIPT

장소 선택 및 공유 구글 API 연습

by 일태찡 2023. 4. 10.

 

기초 세팅

 

index.html

<!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>지도 연습</title>
  <script src="dist/bundle.js" defer></script>
  <link rel="stylesheet" href="app.css">
</head>
<body>
  <div id="map">
    <p>주소를 입력해주세요</p>
  </div>
  <form>
    <input type="text" id="address">
    <button type="submit">찾기</button>
  </form>
</body>
</html>

 

app.css

html {
    font-family: sans-serif;
}

#map {
  width: 90%;
  height: 20rem;
  border: 1px solid #ccc;
  margin: 2rem auto;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

form {
  text-align: center;
  margin: 2rem auto;
}

 

 

입력된 주소의 좌표 가져오기

 

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

 

시작하기  |  Geocoding API  |  Google Developers

지오코딩은 주소를 지리 좌표로 변환하여 지도에 배치합니다. 역지오코딩은 지리 좌표 또는 장소 ID를 기준으로 주소를 찾습니다.

developers.google.com

 

app.ts

import axios from "axios";

const form = document.querySelector("form")!;
const addressInput = document.getElementById("address")! as HTMLInputElement;

const GOOGLE_API_KEY = "발급받은 키를 넣어주세요";

function searchAddressHandler(event: Event) {
  event.preventDefault();
  const enteredAddress = addressInput.value;

  axios
    .get(                                                         // 여기
      `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURI(
        enteredAddress
      )}&key=${GOOGLE_API_KEY}`
    )
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    });
}

form.addEventListener("submit", searchAddressHandler);

 

 

encodeURI는 문자열을 URL 호환 가능한 문자열로 바꿔줍니다.

다음과 같이 코드를 작성하고 수원역을 입력한 다음 콘솔창을 확인해 봅시다.

 

 

 

위와 같이 받아온 데이터를 확인할 수 있으며 이제 데이터를 알맞게 가공해야 합니다.

 

import axios from "axios";

const form = document.querySelector("form")!;
const addressInput = document.getElementById("address")! as HTMLInputElement;

const GOOGLE_API_KEY = "발급받은 키를 넣어주세요";

// 여기
type GoogleGeocodingResponse = {
  results: { geometry: { location: { lat: number; lng: number } } }[];
  status: "OK" | "ZERO_RESULTS";
};

function searchAddressHandler(event: Event) {
  event.preventDefault();
  const enteredAddress = addressInput.value;

  axios // 여기
    .get<GoogleGeocodingResponse>(
      `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURI(
        enteredAddress
      )}&key=${GOOGLE_API_KEY}`
    )
    .then((response) => {
      if (response.data.status !== "OK") {
        throw new Error("주소를 찾을 수 없습니다!");
      }
      const coordinates = response.data.results[0].geometry.location;
    })
    .catch((error) => {
      alert(error.message);
    });
}

form.addEventListener("submit", searchAddressHandler);

 

사용할 데이터인 위도와 경도를 타입으로 미리 지정해 두고 get을 통해 이 데이터를 받아오겠다고 미리 알립니다.

 

 

Google 지도로  지도 렌더링

 

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

 

개요  |  Maps JavaScript API  |  Google Developers

Google Maps JavaScript API를 시작합니다. 간단한 예를 확인하고, 개념을 알아보고, 사이트에 맞는 맞춤 지도를 만들어 보세요.

developers.google.com

 

공식 문서를 참고하여 다음 코드를 html 파일에 추가해 줍니다.

 

<script src="https://maps.googleapis.com/maps/api/js?key=발급받은 키를 넣어주세요" async defer></script>

 

여기서 async 속성은 브라우저에 스크립트 파일이 비동기적으로 실행될 수 있음을 나타내기 위해 사용되며 defer 속성은 HTML 구문 분석이 완전히 완료된 다음 스크립트 파일을 실행하도록 브라우저에게 지시하는 것입니다.

 

app.ts

import axios from "axios";

const form = document.querySelector("form")!;
const addressInput = document.getElementById("address")! as HTMLInputElement;

const GOOGLE_API_KEY = "발급받은 키를 넣어주세요";

declare var google: any; // 1

type GoogleGeocodingResponse = {
  results: { geometry: { location: { lat: number; lng: number } } }[];
  status: "OK" | "ZERO_RESULTS";
};

function searchAddressHandler(event: Event) {
  event.preventDefault();
  const enteredAddress = addressInput.value;

  axios
    .get<GoogleGeocodingResponse>(
      `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURI(
        enteredAddress
      )}&key=${GOOGLE_API_KEY}`
    )
    .then((response) => {
      if (response.data.status !== "OK") {
        throw new Error("주소를 찾을 수 없습니다!");
      }
      const coordinates = response.data.results[0].geometry.location;
      // 2
      const map = new google.maps.Map(document.getElementById("map"), {
        center: coordinates,
        zoom: 16,
      });
      // 3
      new google.maps.Marker({
        position: coordinates,
        map: map,
      });
    })
    .catch((error) => {
      alert(error.message);
    });
}

form.addEventListener("submit", searchAddressHandler);

 

  1. 전역적으로 이용 가능하지만 타입스크립트가 모르기에 알 수 있게 합니다.
  2. 새 지도를 만들고 중심을 검색한 위도 경도로 넣어주고 확대 단계를 16으로 지정합니다.
  3. 같은 위치에 마커도 배치합니다.

 

화질구지 지송합니다...

 

++

 

https://www.npmjs.com/package/@types/google.maps

 

@types/google.maps

TypeScript definitions for Google Maps JavaScript API. Latest version: 3.52.5, last published: 4 days ago. Start using @types/google.maps in your project by running `npm i @types/google.maps`. There are 93 other projects in the npm registry using @types/go

www.npmjs.com

 

위 링크에서 구글맵에 관한 라이브러리를 추가할 수 있습니다.

 

 

이 말은 즉 위와 같이 구글 맵에 관한 코드에 대한 자동완성기능을 제공합니다.

그리고 기존 코드랑 다르게 타입스크립트가 더 이상 google을 모르지 않기 때문에 declare도 삭제할 수 있습니다.

'TYPESCRIPT' 카테고리의 다른 글

리액트와 타입스크립트  (6) 2023.04.11
웹팩(Webpack) 사용하기  (6) 2023.04.07
모듈과 네임스페이스  (6) 2023.04.06
연습 프로젝트 4  (6) 2023.04.04
연습 프로젝트 3  (6) 2023.04.03