LoginSignup
26
15

More than 5 years have passed since last update.

GoogleMapsAPI公式のnpmパッケージは、Promiseも使えるよ

Last updated at Posted at 2017-01-28

Node.jsからGoogleMapAPIを使うにはいくつか方法があると思うのですが、個人的には公式のnpmパッケージが良いです。

googlemaps/google-maps-services-js

インストール

$ npm install @google/maps --save

あるいは、

$ yarn add @google/maps

コールバック関数…?

それで、いざ使ってみようとすると、公式のリファレンスにこんなサンプルコードが。

// Geocode an address.
googleMapsClient.geocode({
  address: '1600 Amphitheatre Parkway, Mountain View, CA'
}, function(err, response) {
  if (!err) {
    console.log(response.json.results);
  }
});

google-maps-services-js#Quick Start

コールバック関数…。
現代のNode.jsアプリケーションの作成において、非同期処理はコールバックではなくPromiseをベースに開発している方が多いかと思います。

そこで、もうちょい調べてみたところ、ありました。

初期化時にPromiseを渡す

まず、初期化時にPromiseを渡します。

const googleMapsClient = require('@google/maps').createClient({
  key: 'your API key here',
  Promise: Promise
})

asPromise() でPromise化

そして、メソッドを実行する時に、asPromise関数をチェーン呼び出しします。
geocodeメソッドを使って座標とアドレス情報を変換するなら以下の通り。

googleMapsClient.geocode({...}).asPromise()

directions メソッドを使って座標から方向を得るなら以下の通り。

googleMapsClient.directions({...}).asPromise()

then, catch, cancel, finally

asPromise でPromise化した場合、then, catch, cancel, finally の4つのチェーンメソッドが使えます。

公式リファレンス: Interface: RequestHandle

26
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
15