Untuk memvalidasi alamat menggunakan Validasi Alamat di Maps JavaScript API, panggil metode fetchAddressValidation
dengan meneruskan isi permintaan dengan alamat yang akan divalidasi, seperti yang ditunjukkan pada 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 komponen individual, atau dengan menggunakan addressLines
untuk meneruskan seluruh alamat yang diformat sebagai literal array (API akan mengurai alamat
menjadi komponen individual):
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 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}`); }