如何获得google place的结果Autocomplete API在变量中返回,而不是将HTML输入结果提供给客户端

时间:2018-04-17 12:39:23

标签: javascript node.js google-maps google-maps-api-3

我正在使用带有angularjs的节点,并希望获得带有地方自动填充功能的Google Places API网络服务。

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

问题是我不想得到结果,因为用户在输入文本中输入内容,如上例所示,但是我想把它放在一个变量中并首先对结果进行一些更改

1 个答案:

答案 0 :(得分:3)

您需要查看Google Maps API documentation。使用AutocompleteService类以编程方式获取预测。 AutocompleteService在Array对象中获取预测,但它不会在地图本身中添加任何UI控件。

  

您可以创建AutocompleteService对象以编程方式检索预测。调用getPlacePredictions()来检索匹配的位置,或调用getQueryPredictions()来检索匹配的位置以及建议的搜索词。注意:AutocompleteService不会添加任何UI控件。相反,上述方法返回预测对象的数组。每个预测对象包含预测的文本,以及参考信息和结果如何与用户输入匹配的细节。

请查看Google Maps API documentation的此部分,了解具体案例。

这是一个带有注释的功能,可以帮助您实现这一结果:

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