Google Places API - place_changed侦听器无法正常工作 [英] Google Places API - place_changed listener not working
问题描述
我尝试使用Google Places API中的自动完成功能。我有自动完成自己设置和工作,但我想添加一个监听器,以便我可以使用PlacesResult其他地方的信息。
为了测试这个功能,我试图通过调出一个警告框并将place.name写入一个。这两个东西都没有工作,所以听众显然被配置为错误,但我无法弄清楚我是如何写错的。
I'm trying to use the autocomplete from the Google Places API. I have the autocomplete itself set up and working, but I want to add a listener so that I can use information from the PlacesResult elsewhere.
To test the functionality, I'm trying to prove the listener is working by bringing up an alert box, and writing the place.name into a . Neither thing is working, so the listener is obviously configured wrong I suppose, but I can't figure out how I've written it wrong.
<!-- Load Places Library for Google Maps-->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false">
</script>
<!-- Autocomplete Script -->
<script type="text/javascript">
function initialize(){
var input = document.getElementById('name');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(autocomplete, 'place_changed', function(){
var place = autocomplete.getPlace();
alert("This function is working!");
document.getElementById("receiver").innerHTML=place.name;
});
</script>
推荐答案
移动 addListener
到 初始化
。
Move the call of addListener
to initialize
.
否则 addListener
将在 之前调用,初始化
, autocomplete
在此时是未知的,并且在此范围内(它不是全局的)
Otherwise addListener
will be called before initialize
, autocomplete
will be unknown at this time and in this scope(it's not global)
这篇关于Google Places API - place_changed侦听器无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!