כדי לאמת כתובת באמצעות Address Validation בממשק API של JavaScript במפות Google, צריך לקרוא ל-method fetchAddressValidation
ולהעביר גוף בקשה עם הכתובת שרוצים לאמת, כפי שמתואר בדוגמה הבאה.
async function validateAddress() { // Import the Address Validation library. const {AddressValidation} = await google.maps.importLibrary('addressValidation'); // Call the fetchAddressValidation method. const result = await AddressValidation.fetchAddressValidation({ address: { postalCode: '94043', regionCode: 'US', languageCode: 'en', addressLines: ['1600 Amphitheatre', 'Parkway'], } }); // Log the results to the console. document.querySelector('pre').textContent = JSON.stringify(result, null, ' '); }
אפשר להגדיר כתובת באמצעות רכיבים נפרדים, או באמצעות addressLines
כדי להעביר את הכתובת הפורמטית כולה כמחרוזת לינרית של מערך (ה-API ינתח את הכתובת
לרכיבים נפרדים):
address: { addressLines: ['1600 Amphitheatre Parkway, Mountain View, CA 94043'], }
טיפול בתוצאות
השיטה fetchAddressValidation
מחזירה הבטחה שמתקבלת בהמרה לאובייקט AddressValidationResponse
. האובייקט הזה מכיל את הכתובת המאומתת, כולל התיקונים שבוצעו על ידי ה-API. אפשר לגשת לשדות השונים של אובייקט התגובה כדי לקבוע את סטטוס האימות של הכתובת. בדוגמה הבאה מוסבר איך לגשת לשדות של אובייקט התגובה.
async function validateAddress() { // Import the Address Validation library. const {AddressValidation} = await google.maps.importLibrary('addressValidation'); // Call the fetchAddressValidation method. const result = await AddressValidation.fetchAddressValidation({ address: { postalCode: '94043', regionCode: 'US', languageCode: 'en', addressLines: ['1600 Amphitheatre', 'Parkway'], } }); // Log the results to the console: console.log(`Formatted address: ${result.address.formattedAddress}`); console.log(`Entered: ${result.verdict.inputGranularity}`); console.log(`Validated: ${result.verdict.validationGranularity}`); console.log(`Address complete: ${result.verdict.addressComplete}`); console.log(`Has unconfirmed components: ${result.verdict.hasUnconfirmedComponents}`); console.log(`Has inferred components: ${result.verdict.hasInferredComponents}`); console.log(`Has replaced components: ${result.verdict.hasReplacedComponents}`); }