Wesley
Wesley

Reputation: 5621

Events other than 'place_changed' for Google Maps Autocomplete

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
});

Upvotes: 54

Views: 60892

Answers (5)

Matthieu Marcé
Matthieu Marcé

Reputation: 172

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;
                    }    
                }  
            }               
        });         
    }
}

Upvotes: 0

Sally CJ
Sally CJ

Reputation: 15620

(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>

Upvotes: 5

MrUpsidown
MrUpsidown

Reputation: 22497

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>

Upvotes: 11

Gleno
Gleno

Reputation: 83

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);
        }
    }
}

Upvotes: 3

geocodezip
geocodezip

Reputation: 161384

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).

Upvotes: 13

Related Questions