Veillez à bien ajouter votre clé API à la place de {API key} dans le premier et second code ci-dessous.
<script src="https://maps.googleapis.com/maps/api/js?key={API key}&libraries=places&callback=initMap" async defer></script>
<script>
"use strict";
function initMap() {
const CONFIGURATION = {
"mapOptions": {"center":{"lat":37.4221,"lng":-122.0841},"fullscreenControl":true,"mapTypeControl":false,"streetViewControl":true,"zoom":11,"zoomControl":true,"maxZoom":22,"mapId":""},
"mapsApiKey": "{API key}",
"capabilities": {"addressAutocompleteControl":true,"mapDisplayControl":false,"ctaControl":false}
};
const addressInput = document.getElementById('address-input');
const autocomplete = new google.maps.places.Autocomplete(addressInput, {
fields: ["address_components", "geometry", "name"],
types: ["address"],
});
autocomplete.addListener('place_changed', function () {
const place = autocomplete.getPlace();
if (!place.geometry) {
window.alert('Aucun détail disponible pour: \'' + place.name + '\'');
return;
}
fillInAddress(place);
});
function fillInAddress(place) {
const addressNameFormat = {
'street_number': 'short_name',
'route': 'long_name',
'locality': 'long_name',
'administrative_area_level_1': 'short_name',
'country': 'long_name',
'postal_code': 'short_name',
};
let completeAddress = "";
function getAddressComp(type) {
for (const component of place.address_components) {
if (component.types[0] === type) {
return component[addressNameFormat[type]];
}
}
return '';
}
completeAddress += getAddressComp('street_number') + ' ' + getAddressComp('route') + ', ';
completeAddress += getAddressComp('locality') + ', ';
completeAddress += getAddressComp('administrative_area_level_1') + ' ';
completeAddress += getAddressComp('postal_code') + ', ';
completeAddress += getAddressComp('country');
addressInput.value = completeAddress;
}
}
</script>