如何在不输入的情况下触发google map places_changed事件

时间:2012-12-28 10:02:09

标签: javascript google-maps-api-3

这是我的代码

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

我想在用户输入字符串

时触发places_changed event

1 个答案:

答案 0 :(得分:3)

您可以在输入更改时轻松触发事件。但是,在调用getPlaces()时,将返回undefined。如果您确实需要键入查询的地点列表,那么您最好使用自动完成服务。

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