Aby sprawdzić poprawność adresu za pomocą interfejsu Address Validation w Maps JavaScript API, wywołaj metodę fetchAddressValidation, przekazując treść żądania z adresem do sprawdzenia, jak pokazano w tym przykładzie.
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, ' '); }
Adres możesz zdefiniować, używając poszczególnych komponentów lub używając addressLines, aby przekazać cały sformatowany adres jako literał tablicy (interfejs API przeanalizuje adres i podzieli go na poszczególne komponenty):
address: { addressLines: ['1600 Amphitheatre Parkway, Mountain View, CA 94043'], }
Obsługa wyników
Metoda fetchAddressValidation zwraca obietnicę, która jest rozwiązywana jako obiekt AddressValidationResponse. Ten obiekt zawiera zweryfikowany adres, w tym wszelkie poprawki wprowadzone przez interfejs API. Aby określić stan weryfikacji adresu, możesz uzyskać dostęp do różnych pól obiektu odpowiedzi. Poniższy przykład pokazuje, jak uzyskać dostęp do pól obiektu odpowiedzi.
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}`); }