如要使用 Maps JavaScript API 中的 Address Validation 驗證地址,請呼叫 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}`); }