Untuk memvalidasi alamat menggunakan Address Validation di Maps JavaScript API, panggil metode fetchAddressValidation
yang meneruskan isi permintaan dengan alamat yang akan divalidasi, seperti yang ditunjukkan dalam contoh berikut.
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, ' '); }
Anda dapat menentukan alamat dengan menggunakan setiap komponen, atau dengan menggunakan addressLines
untuk meneruskan seluruh alamat yang diformat sebagai literal array (API akan mengurai alamat
menjadi setiap komponen):
address: { addressLines: ['1600 Amphitheatre Parkway, Mountain View, CA 94043'], }
Menangani hasil
Metode fetchAddressValidation
menampilkan promise yang diselesaikan ke objek AddressValidationResponse
. Objek ini berisi alamat yang divalidasi,
termasuk koreksi apa pun yang dilakukan oleh API. Anda dapat mengakses berbagai kolom objek respons untuk menentukan status validasi alamat. Contoh berikut menunjukkan cara mengakses kolom objek respons.
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}`); }