Promise

Google Maps JavaScript API 全体の非同期メソッドは、Promise を返します。

サポート

API メソッドが Promise を返すかどうか
経路 はい
距離行列 はい
高度 はい
ジオコーダ はい
最大ズーム画像 はい
プレイス いいえ
Places AutocompleteService 一部1
Streetview はい

用途

Promise の使用方法については、こちらのガイドをご覧ください。Google Maps JavaScript API で非同期メソッド呼び出しを行うには、以下のサンプルをご覧ください。

async と await

await 演算子は、Promise を待機するために使用されます。async 関数内でのみ使用できます。

const app = async () => {
  const elevationService = google.maps.ElevationService();
  const locations = [{lat: 27.986065, lng:86.922623}];

  const response = await elevationService.getElevationForLocation({locations});
  console.log(response.results);
};

app();

then、catch、finally

Promise オブジェクトには、コールバック関数を取得する thencatchfinally の各メソッドがあります。

const elevationService = google.maps.ElevationService();
const locations = [{lat: 27.986065, lng:86.922623}];

const promise = elevationService.getElevationForLocation({locations});

promise
    .then((response) => {
      console.log(response.results);
    })
    .catch((error) => {
      console.log(error);
    });
    .finally(() => {
      console.log('done');
    });

非同期コールバック パターン

コールバック パターンは引き続き有効でサポートされます。

const elevationService = google.maps.ElevationService();
const locations = [{lat: 27.986065, lng:86.922623}];

const callback = (results, status) => {
  if (status === 'OK') {
    console.log(results);
  } else {
    // handle this case
  }
};

elevationService.getElevationForLocation({locations}, callback);

  1. 現在、Promise は getPlacePredictions() でのみサポートされています。