如需在 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
对象的 promise。此对象包含经过验证的地址,包括 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}`); }