تعرض الطرق غير المتزامنة في كل أنحاء Google Maps JavaScript API كائنات Promises.
الدعم
| واجهة برمجة التطبيقات | تعرض الطرق كائنات Promises |
|---|---|
| الاتجاهات | نعم |
| مصفوفة المسافات | نعم |
| الارتفاع | نعم |
| أداة الترميز الجغرافي | نعم |
| صور التكبير الأقصى | نعم |
| أماكن | لا |
| Places AutocompleteService | جزئي1 |
| التجوّل الافتراضي | نعم |
الاستخدام
يمكنك الاطّلاع على هذا الدليل حول استخدام كائنات Promises أو الاطّلاع على الأمثلة أدناه لإجراء استدعاءات الطرق غير المتزامنة باستخدام 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();
الدوال 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);
-
لا تتوافق كائنات Promises حاليًا إلا مع
getPlacePredictions(). ↩