Javascript Google 地图自动完成的“place_changed”以外的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32193020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Events other than 'place_changed' for Google Maps Autocomplete
提问by Wesley
I have an app that currently fires correctly on place_changed.
我有一个当前在 place_changed 上正确触发的应用程序。
However, I want to branch search to behave differently when a user has selected an autocomplete entry, and when they have entered text on their own without the assistance of autocomplete.
但是,当用户选择自动完成条目时,以及当他们在没有自动完成帮助的情况下自行输入文本时,我希望分支搜索的行为有所不同。
What kind of event listener should I use to make the distinction? I cannot find any documentation on other events for Google Maps Autocomplete.
我应该使用什么样的事件监听器来区分?我找不到有关 Google 地图自动完成的其他事件的任何文档。
what I have now:
我现在所拥有的:
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
});
回答by geocodezip
There is only one documented event in the Google Maps Javascript API v3 for the google.maps.places.Autocomplete class, place_changed
Google Maps Javascript API v3 中只有一个记录在案的google.maps.places.Autocomplete 类事件,place_changed
You can add standard HTML event listeners to it (not sure if that will affect the Autocomplete functionality).
您可以向其中添加标准 HTML 事件侦听器(不确定这是否会影响自动完成功能)。
回答by MrUpsidown
This comes down to checking whether you receive a place.geometry
object, as it is shown in their official example. As simple as that!
这归结为检查您是否收到一个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;
}
<input id="autocomplete" placeholder="Enter your address" type="text"></input>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
回答by Gleno
If you add your own input handler (for example catching CR after user entering his own text), autocomplete and your function may call your method back to back. My solution is to use throttle to avoid the repeated call:
如果您添加自己的输入处理程序(例如在用户输入他自己的文本后捕获 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);
}
}
}
回答by Sally CJ
(Updated answer — Oct 18th2018 UTC)
(更新的答案 - UTC 时间 2018年 10 月 18日)
The place_changed
documentationsays:
该place_changed
文件说:
If the user enters the name of a Place that was not suggested by the controland presses the Enter key, or if a Place Detailsrequest fails, the PlaceResult contains the user input in the nameproperty, with no other propertiesdefined.
如果用户输入控件未建议的 Place 名称并按下 Enter 键,或者如果Place Details请求失败,PlaceResult 将在name属性中包含用户输入,没有定义其他属性。
So (as I mentioned in my comment), we can check if the property name
is the onlyproperty in the PlaceResult
object retrieved via Autocomplete.getPlace()
. See and try the code snippet below:
所以(正如我在评论中提及),我们可以检查,如果该属性name
是唯一的财产PlaceResult
通过检索对象Autocomplete.getPlace()
。查看并尝试下面的代码片段:
(If the API key doesn't work, use your own.)
(如果 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 );
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBMPpy3betC_QCBJtc3sC4BtEIYo4OYtPU&libraries=places"></script>
<input id="searchproperties" placeholder="Search places">
<div id="test"></div>
回答by Matthieu Marcé
This is quite an old question but i propose a solution that could be lot simplier than what i read here.
这是一个很老的问题,但我提出了一个解决方案,它可能比我在这里读到的要简单得多。
The 'place_changed' event only fires when a user actually select a suggestion from Google's list.
'place_changed' 事件仅在用户实际从 Google 列表中选择建议时触发。
So as long as the user did not select a suggestion, you can consider that the text entered in the input is not a google's place result.
所以只要用户没有选择suggestion,就可以认为input中输入的文字不是google的地方结果。
From here, you could consider 'place-changed' as a kind of 'click' event, using a boolean to store the current state
从这里开始,您可以将 'place-changed' 视为一种 'click' 事件,使用布尔值来存储当前状态
function initializeAutocomplete(id) {
var element = document.getElementById(id);
if (element) {
var autocomplete = new google.maps.places.Autocomplete(element, { types: ['geocode','establishment'], componentRestrictions: {country: ['fr']} });
google.maps.event.addListener(autocomplete, 'place_changed', function(){
var place = this.getPlace();
console.log("A result from "+id+" was clicked !");
for (var i in place.address_components) {
var component = place.address_components[i];
for (var j in component.types) {
var type_element = document.getElementById(component.types[j]);
if (type_element) {
type_element.value = component.long_name;
}
}
}
});
}
}