Michael
Michael

Reputation: 19

google.maps.places.Autocomplete call on blur, results in "Cannot read property 'geometry' of undefined"

Here is the error I get running following code:

Error: Uncaught TypeError: Cannot read property 'geometry' of undefined

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var places = new google.maps.places.Autocomplete(document.getElementById('bodyOfWater'));
google.maps.event.addDomListener(window, 'load', function () {
	//On select of the location
	google.maps.event.addListener(places, 'place_changed', function () {
		var place = places.getPlace();
		alert(place.geometry.location.lat());
	});
	
	// Trigger search on blur
	/*=====================*/
	/* PROBLEM IN FOLLOWING CODE*/
	/*=====================*/
	google.maps.event.addDomListener(document.getElementById('bodyOfWater'), 'blur', function() {
		var place = places.getPlace();
		alert(place.geometry.location.lat());;
	});
});
</script>

First part works properly when I actually select a place from google, but when I try to trigger same action on blur, looks like that I do not get place back.

Upvotes: 0

Views: 1345

Answers (1)

geocodezip
geocodezip

Reputation: 161384

The places API is asynchronous. You can't get the result until it comes back from the server (when the place_changed event fires).

Upvotes: 1

Related Questions