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() を呼び出すと undefined が返されます。入力されたクエリの場所のリストが実際に必要な場合は、オートコンプリート サービスを使用することをお勧めします。

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

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

EDIT以下は、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 に答える