Adresse bestätigen

Wenn Sie eine Adresse mit der Address Validation API in der Maps JavaScript API validieren möchten, rufen Sie die Methode fetchAddressValidation auf und übergeben Sie einen Anfragetext mit der zu validierenden Adresse, wie im folgenden Beispiel gezeigt.

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, '  ');
}
    

Sie können eine Adresse mithilfe einzelner Komponenten oder mit addressLines definieren, um die gesamte formatierte Adresse als Arrayliteral zu übergeben. Die API analysiert die Adresse dann in einzelne Komponenten:

address: {
  addressLines: ['1600 Amphitheatre Parkway, Mountain View, CA 94043'],
}
    

Ergebnisse verarbeiten

Die fetchAddressValidation-Methode gibt ein Versprechen zurück, das in ein AddressValidationResponse-Objekt aufgelöst wird. Dieses Objekt enthält die validierte Adresse, einschließlich aller Korrekturen, die von der API vorgenommen wurden. Sie können auf die verschiedenen Felder des Antwortobjekts zugreifen, um den Validierungsstatus der Adresse zu ermitteln. Das folgende Beispiel zeigt, wie Sie auf die Felder des Antwortobjekts zugreifen.

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}`);
}
    

Nächste Schritte