Hi All,
I have gotten google autocomplete to work, but just in case the user doesn't select the autocomplete, I am trying to submit the address to google and retrieve the latitude and longitude myself.
The issue I am having is when I submit without using autocomplete I am getting Uncaught TypeError: Cannot read property 'geometry' of undefined and Uncaught TypeError: Cannot read property 'location' of undefined (none of my console.logs are triggered).
If I submit with auto complete I still get Uncaught TypeError: Cannot read property 'geometry' of undefined even though the autocomplete did work to get the address with the lat and long.
My Html
<form method="GET" id="my-form" action="/search" onsubmit="check()">
<input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
<input id="latitude" type="hidden" name="latitude">
<input id="longitude" type="hidden" name="longitude">
</form>
I call geo() for autocompleteing, but incase they don't use the autocomplete, I try to catch it on submit with my check() function. Here is my JS
function check() {
let latitude = document.getElementById("latitude").value;
if (latitude) {
console.log(latitude);
} else {
let term = $("#getaddy").val();
$.ajax({
url: "https://maps.googleapis.com/maps/api/geocode/json?address="+encodeURIComponent(term) +"&key=GOOGLEKEY",
type: 'get',
success: function(data) {
if (data.status === 'OK') {
// Get the lat/lng from the response
let lat = data.results[0].geometry.location.lat;
let lng = data.results[0].geometry.location.lng;
console.log("pass");
}
},
error: function(msg) {
console.log("fail");
}
});
return true;
}
}
function geo() {
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('getaddy')), {
types: ['geocode']
});
autocomplete.addListener('place_changed', addlatlong);
}
function addlatlong() {
var place = autocomplete.getPlace();
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
}
Thank you so much for any help!