כדי לאמת כתובת באמצעות 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}`); }