4

这是我的代码

searchBox = new google.maps.places.SearchBox(input);
google.maps.event.addListener(searchBox,"places_changed",that.search);

我想places_changed event 在用户输入字符串时触发

4

1 回答 1

3

当输入改变时,您可以轻松触发事件。但是,当调用 getPlaces() 时,您将得到未定义的返回。如果您确实想要输入查询的位置列表,那么您最好使用自动完成服务。

https://developers.google.com/maps/documentation/javascript/reference#AutocompleteService

input.on('keydown', function() {
    google.maps.event.trigger(searchBox, 'places_changed');
});

编辑下面是如何使用 AutocompleteService 的示例

<!doctype html>
<html>
<head>
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
    <script>
        var init = function() {
            var query = document.getElementById('query'),
                autocomplete = new google.maps.places.AutocompleteService();

            query.addEventListener('keyup', function() {
                if (this.value.length === 0) {
                    return;
                }
                autocomplete.getPlacePredictions({input: this.value}, function(predictions, status) {
                    if (status === google.maps.places.PlacesServiceStatus.OK) {
                        console.log(predictions);
                    }
                });
            });
        }
    </script>
</head>
<body onload="init()">
    <input type="text" id="query" placeholder="Search">
</body>
</html>

如果用户正在输入某些内容,那么您可能不想在他们每次输入字符时都进行搜索。因此,您可以在进行搜索之前设置一个计时器。

var searchWait;
query.addEventListener('keyup', function() {
    // make sure we clear any previous timers before setting a new one
    clearTimeout(searchWait); 

    if (this.value.length === 0) {
        return;
    }
    searchWait = setTimeout(function(searchValue) {
        return function() {
            autocomplete.getPlacePredictions({input: searchValue}, function(predictions, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    console.log(predictions);
                }
            });
        }
    }(this.value), 500);
});
于 2012-12-30T06:20:35.013 回答