Fleur
Fleur

Reputation: 686

Google Places Autocomplete 'place_changed' event not working

I have set up the autocomplete text box and it shows the options. However the 'place_changed' event returns [object Object] as the output. Below is my code.

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en"></script>

<script>
    var pos;
    var mylocation;
    function initAutocomplete(){
        var input = document.getElementById('autocomplete');
        var autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addListener(autocomplete, 'place_changed', function(){
            mylocation = autocomplete.getPlace();
            alert(mylocation);
        })
    }
</script>

Below is the CSS I've used:

#pac-input {
    background-color: #fff;
    font-size: 15px;
    font-weight: 300;
    margin-left: 12px;
    padding: 0 11px 0 13px;
    text-overflow: ellipsis;
    width: 350px;
}

#pac-input:focus {
    border-color: #4d90fe;
}

.pac-container {
    z-index: 2000000 !important;
    width: 350px;
}

.pac-item {
    height: 35px;
    font-size: 12px;
    color: #101010;
}

#autocomplete {
    height: 35px;
    width: 100%;
    padding-left: 10px;
}

Any help to fix this would be appreciated.

Upvotes: 2

Views: 7958

Answers (1)

John
John

Reputation: 4991

In your event declaration remove the autocomplete parameter :

google.maps.event.addListener('place_changed', function()

instead of :

google.maps.event.addListener(autocomplete, 'place_changed', function()

And try this alert :

alert(mylocation.name);

mylocationis a JSON object. Try to do console.log(mylocation) to recover the JSON key and the value. If you alert mylocation it's normal. This alert will returns [object Object] because it's a JSON object.

Upvotes: 2

Related Questions