I am getting some errors when I click on any prediction from the google places autocomplete dropdown of predictions. From what I've discovered it getPlace() returns "undefined" the first time it's triggered, but then it returns the address the second time around.

first click on a prediction from autocomplete dropdown

second click on the prediction

maps script

code for autocomplete

as can be seen in the code, I'm having a difficult time understanding why the getPlace doesn't return a place even though the listener triggers the onPlaceChanged(), and I'm not sure if the errors are the root of the problem, but if anyone has any clues so that i can get a different error to work with that would be appreciated.

1

There are 1 best solutions below

0
R00M On

I changed the logic for getting the clicked prediction and now it works correctly, thanks to the answer this question: Google maps API autocomplete.getPlace() inconsistently returns geometry

let autcompleteInput: HTMLInputElement;

    function initializeAutocomplete() {
        if (autcompleteInput != null) {
            var searchBox = new google.maps.places.SearchBox(autcompleteInput);
            searchBox.addListener('places_changed', ()=>{
                var place = searchBox.getPlaces();
                if (place) {
                    handleGooglePlacesPress(place.at(0)!)
                }
            })
        }
    }

    function handleGooglePlacesPress(details: google.maps.places.PlaceResult) {
        const addressComponents = details.address_components;
        if (addressComponents) {
            addressComponents.forEach((addressComponent) => {
                const addressType = addressComponent.types[0];
                if (addressType == 'street_number') {appartmentSuiteNum = addressComponent.long_name;}
                if (addressType == 'route') {address = addressComponent.long_name;}
                if (addressType == 'sublocality_level_1') {city = addressComponent.long_name;}
                if (addressType == 'locality') {city = addressComponent.long_name;}
                if (addressType == 'administrative_area_level_1') {county = addressComponent.long_name;}
                if (addressType == 'postal_code') {postcode = addressComponent.long_name;}
                if (addressType == 'country') {country = addressComponent.long_name;}
            });
        }
    }