Google地图自动填充function除“place_changed”以外的其他活动

我有一个应用程序,目前正在place_changed正确激活。

但是,我想分支搜索,以便在用户选择自动填充条目时,以及在没有自动完成帮助的情况下自己输入文本时表现不同。

我应该使用什么样的事件监听器来区分? 我无法找到有关Google地图自动填充的其他活动的任何文档。

我现在拥有的:

var gmaps = new google.maps.places.Autocomplete($("#searchproperties").get(0), { types: ['geocode'], componentRestrictions: {country: 'us'} }); google.maps.event.addListener(gmaps, 'place_changed', function () { //FIRE SEARCH }); 

Google Maps Javascript API v3中只有一个针对google.maps.places.Autocomplete类的文档事件, place_changed

您可以向其添加标准HTML事件侦听器(不确定这是否会影响自动完成function)。

如果您添加自己的输入处理程序(例如在用户输入自己的文本后捕获CR),则自动完成并且您的函数可以背靠背调用您的方法。 我的解决方案是使用油门避免重复调用:

 $('#sell_address_input').keyup(function(e){ if(e.keyCode==13){throttle(addressEntered(),1000)}}); 

….

 function throttle(callback, limit) { var wait = false; // Initially, we're not waiting return function () { // We return a throttled function if (!wait) { // If we're not waiting callback.call(); // Execute users function wait = true; // Prevent future invocations setTimeout(function () { // After a period of time wait = false; // And allow future invocations }, limit); } } } 

这归结为检查是否收到place.geometry对象,如其官方示例中所示。 就如此容易!

 function initialize() { var ac = new google.maps.places.Autocomplete( (document.getElementById('autocomplete')), { types: ['geocode'] }); ac.addListener('place_changed', function() { var place = ac.getPlace(); if (!place.geometry) { // User entered the name of a Place that was not suggested and // pressed the Enter key, or the Place Details request failed. // Do anything you like with what was entered in the ac field. console.log('You entered: ' + place.name); return; } console.log('You selected: ' + place.formatted_address); }); } initialize(); 
 #autocomplete { width: 300px; } 
   

(更新的答案 – 2018年10月18 UTC)

place_changed 文档说:

如果用户输入控件未建议的Place的名称并按Enter键,或者Place Details请求失败,则PlaceResult将在name属性中包含用户输入, 而不定义其他属性

所以(正如我在评论中提到的),我们可以检查属性name是否是通过Autocomplete.getPlace()检索的PlaceResult对象中的唯一属性。 请参阅并尝试以下代码段:

(如果API密钥不起作用,请使用自己的密钥。)

 var gmaps = new google.maps.places.Autocomplete($("#searchproperties").get(0), { types: ['geocode'], componentRestrictions: {country: 'us'} }); google.maps.event.addListener(gmaps, 'place_changed', function () { var place = gmaps.getPlace(), has_name = ( place && undefined !== place.name ), count = 0; // Iterates through `place` and see if it has other props. $.each( place || {}, function(){ if ( count > 1 ) { // No need to count all; so let's break the iteration. return false; } count++; }); if ( has_name && count < 2 ) { $('#test').html( 'You didn\'t make a selection and typed: ' + place.name ); } else { $('#test').html( 'You selected: ' + place.formatted_address ); } });