HTML:
<input type="text" id="address" name="address" value=""> //Autocomplete input address
<input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
<input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude
Javascript:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
<script>
var input = document.getElementById('address');
var originLatitude = document.getElementById('s_latitude');
var originLongitude = document.getElementById('s_longitude');
var originAutocomplete = new google.maps.places.Autocomplete(input);
originAutocomplete.addListener('place_changed', function(event) {
var place = originAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
originLatitude.value = place.geometry.location.lat();
originLongitude.value = place.geometry.location.lng();
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
originLatitude.value = results[0].geometry.location.lat();
originLongitude.value = results[0].geometry.location.lng();
}
});
}
});
</script>