Events other than 'place_changed' for Google Maps Autocomplete

JavascriptJqueryGoogle MapsGoogle Maps-Api-3Autocomplete

Javascript Problem Overview


I have an app that currently fires correctly on place_changed.

However, I want to branch search to behave differently when a user has selected an autocomplete entry, and when they have entered text on their own without the assistance of autocomplete.

What kind of event listener should I use to make the distinction? I cannot find any documentation on other events for Google Maps Autocomplete.

what I have now:

var gmaps = new google.maps.places.Autocomplete($("#searchproperties").get(0), 
{ types: ['geocode'], componentRestrictions: {country: 'us'} });

google.maps.event.addListener(gmaps, 'place_changed', function () {
    //FIRE SEARCH
});

Javascript Solutions


Solution 1 - Javascript

There is only one documented event in the Google Maps Javascript API v3 for the google.maps.places.Autocomplete class, place_changed

You can add standard HTML event listeners to it (not sure if that will affect the Autocomplete functionality).

Solution 2 - Javascript

This comes down to checking whether you receive a place.geometry object, as it is shown in their official example. As simple as that!

function initialize() {

  var ac = new google.maps.places.Autocomplete(
    (document.getElementById('autocomplete')), {
      types: ['geocode']
    });

  ac.addListener('place_changed', function() {

    var place = ac.getPlace();

    if (!place.geometry) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      // Do anything you like with what was entered in the ac field.
      console.log('You entered: ' + place.name);
      return;
    }

    console.log('You selected: ' + place.formatted_address);
  });
}

initialize();

#autocomplete {
  width: 300px;
}

<input id="autocomplete" placeholder="Enter your address" type="text"></input>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>

Solution 3 - Javascript

If you add your own input handler (for example catching CR after user entering his own text), autocomplete and your function may call your method back to back. My solution is to use throttle to avoid the repeated call:

$('#sell_address_input').keyup(function(e){ if(e.keyCode==13){throttle(addressEntered(),1000)}});

....

function throttle(callback, limit) {
    var wait = false;             // Initially, we're not waiting
    return function () {          // We return a throttled function
        if (!wait) 
        {                         // If we're not waiting
          callback.call();        // Execute users function
          wait = true;            // Prevent future invocations
          setTimeout(function () 
          {                       // After a period of time
            wait = false;         // And allow future invocations
          }, limit);
        }
    }
}

Solution 4 - Javascript

(Updated answer — Oct 18th 2018 UTC)

The place_changed documentation says:

> If the user enters the name of a Place that was not suggested by the control and presses the Enter key, or if a Place Details request > fails, the PlaceResult contains the user input in the name > property, with no other properties defined.

So (as I mentioned in my comment), we can check if the property name is the only property in the PlaceResult object retrieved via Autocomplete.getPlace(). See and try the code snippet below:

(If the API key doesn't work, use your own.)

var gmaps = new google.maps.places.Autocomplete($("#searchproperties").get(0), 
{ types: ['geocode'], componentRestrictions: {country: 'us'} });

google.maps.event.addListener(gmaps, 'place_changed', function () {
  var place = gmaps.getPlace(),
    has_name = ( place && undefined !== place.name ),
    count = 0;

  // Iterates through `place` and see if it has other props.
  $.each( place || {}, function(){
    if ( count > 1 ) {
      // No need to count all; so let's break the iteration.
      return false;
    }
    count++;
  });

  if ( has_name && count < 2 ) {
    $('#test').html( 'You didn\'t make a selection and typed: ' + place.name );
  } else {
    $('#test').html( 'You selected: ' + place.formatted_address );
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMPpy3betC_QCBJtc3sC4BtEIYo4OYtPU&libraries=places"></script>

<input id="searchproperties" placeholder="Search places">
<div id="test"></div>

Solution 5 - Javascript

This is quite an old question but i propose a solution that could be lot simplier than what i read here.

The 'place_changed' event only fires when a user actually select a suggestion from Google's list.

So as long as the user did not select a suggestion, you can consider that the text entered in the input is not a google's place result.

From here, you could consider 'place-changed' as a kind of 'click' event, using a boolean to store the current state

function initializeAutocomplete(id) {  
	var element = document.getElementById(id);    
	if (element) {    
		var autocomplete = new google.maps.places.Autocomplete(element, { types: ['geocode','establishment'], componentRestrictions: {country: ['fr']} });
		google.maps.event.addListener(autocomplete, 'place_changed', function(){
			var place = this.getPlace();
            console.log("A result from "+id+" was clicked !");
			for (var i in place.address_components) {    
				var component = place.address_components[i];    
				for (var j in component.types) {  
					var type_element = document.getElementById(component.types[j]);      
					if (type_element) {        
    					type_element.value = component.long_name;
	      			}    
			    }  
			}				
		});			
	}
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWesleyView Question on Stackoverflow
Solution 1 - JavascriptgeocodezipView Answer on Stackoverflow
Solution 2 - JavascriptMrUpsidownView Answer on Stackoverflow
Solution 3 - JavascriptGlenoView Answer on Stackoverflow
Solution 4 - JavascriptSally CJView Answer on Stackoverflow
Solution 5 - JavascriptMatthieu MarcéView Answer on Stackoverflow