เมธอดแบบอะซิงโครนัสใน Google Maps JavaScript API จะแสดงผล Promise
การสนับสนุน
API | เมธอดจะคืนค่า Promise |
---|---|
เส้นทาง | ใช่ |
เมทริกซ์ระยะทาง | ใช่ |
ระดับความสูง | ใช่ |
Geocoder | ใช่ |
ภาพที่มีการซูมสูงสุด | ใช่ |
สถานที่ | ไม่ |
Places AutocompleteService | บางส่วน1 |
Streetview | ใช่ |
การใช้งาน
ดูคู่มือ นี้เกี่ยวกับการใช้ Promise หรือตัวอย่างด้านล่างเพื่อทำการเรียกเมธอดแบบไม่พร้อมกัน ด้วย Google Maps JavaScript API
Async และ await
โอเปอเรเตอร์ await ใช้เพื่อรอ 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'); });
รูปแบบการเรียกกลับแบบไม่พร้อมกัน
รูปแบบการเรียกกลับ ยังคงใช้งานได้และได้รับการรองรับ
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);
-
ปัจจุบันรองรับเฉพาะใน
getPlacePredictions()
เท่านั้น ↩