Events other than 'place_changed' for Google Maps Autocomplete

前端 未结 5 669
庸人自扰
庸人自扰 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:48

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

提交回复
热议问题