Google Maps API Client Library for node.js (google-maps-services-js)

김혜지·2020년 10월 21일
0

Google Maps Platform 에서는 Server-side 개발을 위해 Client Library를 제공한다. 라이브러리를 제공해주는 것은 감사하나 사용 예제가 거의 없고 Repository의 README를 제외한 어떠한 문서도 찾지 못해 처음에 꽤 난감했다. (혹시 있으면 알려주세요..!!)

기본적으로 Google API를 사용하기 위한 모든 준비는 되어있다고 가정한다. 아직 준비가 되지 않았다면 이 포스팅을 참고하여 완료하길 바란다.

Client libraries Overview

Client Libraries for Google Maps Web Services Link

Server-side와 Client-side를 위해 각 언어에 대한 Client Library를 제공하고 있다. 위 링크에 각 라이브러리에 대한 GitHub 링크를 제공하며 장점에 대해 간략하게 설명한다. 이 포스팅에서는 Node.js를 위한 라이브러리 google-maps-services-js를 사용한다.

google-maps-services-js

googlemaps/google-maps-services-js GitHub Link

Node.js Client for Google Maps에서 사용할 수 있는 라이브러리이다.
server-side Node.js 어플리케이션 용으로 설계되어 리엑트 네이티브와 같은 다른 환경에서의 사용은 추천하지 않는다고 한다.

Install

npm install @googlemaps/google-maps-services-js

Example

다음은 클라이언트 클래스에서 elevation(고도) 메서드를 호출하는 간단한 예이다. Elevation API에 포함되어 있으므로, 이 예제를 진행하기 전에 Google Cloud Platform 콘솔에서 해당 API를 사용 상태로 만들어줘야 한다.
먼저 라이브러리로부터 Google Maps Client를 가져온다.

const { Client } = require("@googlemaps/google-maps-services-js");

이제 클라이언트를 인스턴스화하여 API 중 하나를 호출한다.

const client = new Client({});

client
  .elevation({
    params: {
      locations: [{ lat: 45, lng: -110 }],
      key: "asdf",
    },
    timeout: 1000, // milliseconds
  })
  .then((r) => {
    console.log(r.data.results[0].elevation);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });

코드를 동작시켜 확인해보면 아래 값이 나온다.

2267.643310546875
const client = new Client({})
const params = {
  location: { lat: 35, lng: -110 },
  radius: 50000,
  key: process.env.GOOGLE_MAPS_API_KEY,
}

try {
  const r = await client.placesNearby({ params: params })
  console.log(r.data.results)
  res.json(r.data.results)
} catch (e) {
  res.json(e)
}
profile
Developer ( Migrating from https://hyex.github.io/ )

0개의 댓글