Reputation: 3512
I'm letting users add an address to their posts using Google Maps.
If a user enters nothing for the map or enters odd special characters (#$!@#) it crashes the website and gives me this error:
var lat = data.results[0].geometry.location.lat;
^
TypeError: Cannot read property 'results' of undefined
I'm trying to figure out a way to check for this error when the form is submitted. So far I have had zero luck. Is it possible to check for this error?
I've seen code like this but everything in undefined and I'm not sure how to define it in this case and frankly I'm not sure how the code below is operating.
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lon = results[0].geometry.location.lng();
searchStores(lat, lon);
} else {
$addressErrorP.removeClass('hide');
}
Thanks for any help!
Upvotes: 2
Views: 5138
Reputation: 3512
Figured it out: Simple and works perfectly.
Step 1: Make sure this is on your page.
<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
Then
$('#checkingAddress').click(checkGeocode)
function checkGeocode() {
var addr = document.getElementById('location')
// Get geocoder instance
var geocoder = new google.maps.Geocoder()
// Geocode the address
geocoder.geocode({ address: addr.value }, function (results, status) {
if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
alert('looks good')
// set it to the correct, formatted address if it's valid
addr.value = results[0].formatted_address
// show an error if it's not
} else alert('Invalid address')
})
}
Upvotes: 1