หากต้องการตรวจสอบที่อยู่โดยใช้ Address Validation ใน Maps JavaScript API ให้เรียกใช้เมธอด 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}`); }