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