Events other than 'place_changed' for Google Maps Autocomplete

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

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

提交回复
热议问题