คํามั่นสัญญา

เมธอดแบบไม่พร้อมกันทั่วทั้ง Google Maps JavaScript API จะแสดง Promises

การสนับสนุน

API เมธอดแสดง "คำสัญญา"
คำแนะนำ ได้
เมทริกซ์ระยะทาง ได้
ระดับความสูง ได้
โปรแกรมเข้ารหัสพิกัดภูมิศาสตร์ ได้
ภาพที่ซูมสูงสุด ได้
สถานที่ ไม่ได้
บริการเติมข้อความอัตโนมัติเกี่ยวกับสถานที่ บางส่วน1
Street View ได้

การใช้งาน

ดูคำแนะนำนี้เกี่ยวกับการใช้ Promises หรือตัวอย่างด้านล่างสำหรับการเรียกเมธอดแบบไม่พร้อมกันด้วย Google Maps JavaScript API

ไม่พร้อมกันและรอ

ระบบใช้ โอเปอเรเตอร์รอคอย เพื่อรอ Promise โดยใช้ได้เฉพาะในฟังก์ชันอะซิงโครนัสเท่านั้น

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();

ต่อไป จับ และสุดท้าย

ออบเจ็กต์ Promise มีเมธอด then, catch และ finally ที่ใช้ฟังก์ชัน Callback

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');
    });

รูปแบบ Callback แบบไม่พร้อมกัน

รูปแบบ Callback ยังคงถูกต้องและรองรับ

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. ปัจจุบัน Promises ได้รับการสนับสนุนเฉพาะในgetPlacePredictions()