2012-12-28 22 views

回答

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

謝謝你,你能不能給我一個約AutocompleteService – lxg

+0

@Mr演示。劉我已經更新了我的答案使用谷歌,包括演示AutocompleteService –

+0

非常感謝你對我來說是非常 – lxg