lxg
lxg

Reputation: 215

how to fire google map places_changed event without enter

Here is my code

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

I want to trigger places_changed event When user input string

Upvotes: 3

Views: 7733

Answers (1)

Seain Malkin
Seain Malkin

Reputation: 2303

You can easily trigger the event when the input is changed. However you will get undefined returned when calling getPlaces(). If you actually want a list of places for the typed query then you may be better off using the autocomplete service.

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

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

EDIT Below is an example of how to use the 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>

If the user is typing something out, then you probably don't want to search everytime they enter a character. So you could set a timer before doing the search.

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

Upvotes: 4

Related Questions