简体   繁体   中英

How to get result of google place Autocomplete API returned in a variable instead of serving result in HTML input element to the client

I'm using node with angularjs and want to get cities with Place Autocomplete, Google Places API Web Service.

  var autocomplete = new google.maps.places.Autocomplete(yourHTMLElement,{types: ['(cities)']});

The problem is that I don't want to get the result as the users are typing inside the input text like in the example above, but I want to put it in a variable and do some changes with the result first

You need to look into the Google Maps API documentation for this. Use the AutocompleteService class to get prediction programmatically. The AutocompleteService get the prediction in an Array object but it does not add any UI controls in the map itself.

You can create an AutocompleteService object to retrieve predictions programmatically. Call getPlacePredictions() to retrieve matching places, or call getQueryPredictions() to retrieve matching places plus suggested search terms. Note: AutocompleteService does not add any UI controls. Instead, the above methods return an array of prediction objects. Each prediction object contains the text of the prediction, as well as reference information and details of how the result matches the user input.

Take a look also at this section of the Google Maps API documentation for your specific case.

This is a function with comments that will help you achieving that result:

function initService() {
    const displaySuggestions = (predictions, status) => {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert(status);
            return;
        }

        // use forEch method to populate the
        // returned preditions in the Array
        predictions.forEach(prediction => {

            // here you can use an NG directive in your Angular app
            let li = document.createElement('li');
            li.appendChild(document.createTextNode(prediction.description));
            document.getElementById('results').appendChild(li);
        });
    };

    // change the string inside the input property as you wish and get the predicted list stored in a variable
    const service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({
        input: 'pizza near roma'
    }, displaySuggestions);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM