Events other than 'place_changed' for Google Maps Autocomplete

前端 未结 5 670
庸人自扰
庸人自扰 2020-12-25 09:57

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,

5条回答
  •  温柔的废话
    2020-12-25 10:40

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

提交回复
热议问题