Để xác thực địa chỉ bằng tính năng Xác thực địa chỉ trong API JavaScript của Maps, hãy gọi phương thức fetchAddressValidation
, truyền nội dung yêu cầu có địa chỉ cần xác thực, như trong ví dụ sau.
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, ' '); }
Bạn có thể xác định địa chỉ bằng cách sử dụng các thành phần riêng lẻ hoặc bằng cách sử dụng addressLines
để truyền toàn bộ địa chỉ đã định dạng dưới dạng một giá trị cố định mảng (API sẽ phân tích cú pháp địa chỉ thành các thành phần riêng lẻ):
address: { addressLines: ['1600 Amphitheatre Parkway, Mountain View, CA 94043'], }
Xử lý kết quả
Phương thức fetchAddressValidation
trả về một lời hứa phân giải thành đối tượng AddressValidationResponse
. Đối tượng này chứa địa chỉ đã được xác thực, bao gồm mọi nội dung sửa đổi do API thực hiện. Bạn có thể truy cập vào nhiều trường của đối tượng phản hồi để xác định trạng thái xác thực của địa chỉ. Ví dụ sau đây cho biết cách truy cập các trường của đối tượng phản hồi.
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}`); }