Google Maps JavaScript API 中的非同步方法會傳回 Promise。
支援
| API | 方法是否傳回 Promise | 
|---|---|
| 路線 | 是 | 
| 距離矩陣 | 是 | 
| 海拔高度 | 是 | 
| 地理編碼器 | 是 | 
| 最大縮放圖像 | 是 | 
| 地點介面集 | 否 | 
| Place Autocomplete 服務 | 部分1 | 
| 街景服務 | 是 | 
使用方式
請參閱這份指南瞭解如何使用 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 物件具有可採用回呼函式的 then、catch 和 finally 方法。
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);
- 
Promise 目前只能在 getPlacePredictions()中使用。 ↩