Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Places API - place_changed listener not working

I'm trying to use the autocomplete from the Google Places API. I have the autocomplete itself set up and working, but I want to add a listener so that I can use information from the PlacesResult elsewhere.

To test the functionality, I'm trying to prove the listener is working by bringing up an alert box, and writing the place.name into a . Neither thing is working, so the listener is obviously configured wrong I suppose, but I can't figure out how I've written it wrong.

<!-- Load Places Library for Google Maps-->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false">
</script>

<!-- Autocomplete Script -->
<script type="text/javascript">
function initialize(){
    var input = document.getElementById('name');
    var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);

google.maps.event.addListener(autocomplete, 'place_changed', function(){
    var place = autocomplete.getPlace();
    alert("This function is working!");
    document.getElementById("receiver").innerHTML=place.name;
});
</script>
like image 793
kinkersnick Avatar asked Oct 08 '22 09:10

kinkersnick


1 Answers

Move the call of addListener to initialize .

Otherwise addListener will be called before initialize , autocomplete will be unknown at this time and in this scope(it's not global)

like image 199
Dr.Molle Avatar answered Oct 17 '22 06:10

Dr.Molle