javascript 更改 Google 地图自动完成字段的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21658972/
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
Change value of Google Maps Autocomplete field
提问by user1032531
How do I change the value of a Google Maps autocomplete field after the value has been changed?
更改值后,如何更改 Google 地图自动完成字段的值?
My ultimate desire is to just show the address in this field, and the city, state, etc in separate fields.
我的最终愿望是只在该字段中显示地址,在不同的字段中显示城市、州等。
As seen by http://jsbin.com/wiye/2/(script duplicated below), I change the value, but it later changes back.
正如http://jsbin.com/wiye/2/(下面复制的脚本)所见,我更改了值,但后来又改回来了。
show just the street address in google.maps.event.addListener()asks the same question, but it no longer appears to work. Change the value in textbox of a google map autocompletealso asks the same question, but doesn't have an adequate answer.
show just the street address in google.maps.event.addListener()提出了同样的问题,但它似乎不再起作用。 Change the value in textbox of a google map autocomplete也会问同样的问题,但没有足够的答案。
Thank you
谢谢
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Places search box</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
$(function(){
var input_auto = document.getElementById('input_auto');
autocomplete = new google.maps.places.Autocomplete(input_auto,{types: ['geocode'],radius: 10});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
setTimeout(function(){$('#input_auto').val('yyy');},50);
alert('pause1');
console.log(autocomplete,input_auto);
input_auto.value='xxx';
//autocomplete.set('xxx');
//autocomplete.setValues('xxx');
alert('pause2');
});
});
</script>
</head>
<body>
<input id="input_auto" type="text">
</body>
</html>
回答by SwankyLegg
You're using a number of events that you don't need. When a user selects an address from the autocomplete options, autocomplete fires the place_changed
event. When that event fires, autocomplete populates the field that it's attached to.
您正在使用一些不需要的事件。当用户从自动完成选项中选择一个地址时,自动完成会触发该place_changed
事件。当该事件触发时,自动完成会填充它所附加到的字段。
Here's a more appropriately-structured answer to your problem that will enable you to "show the address in this field, and the city, state, etc in separate fields":
这是针对您的问题的结构更合理的答案,可以让您“在此字段中显示地址,在不同的字段中显示城市、州等”:
(function() {
var $inputAuto = $('#input_auto');
var addrComponents = {
streetNumber: {
display: 'short_name',
type: 'street_number'
},
streetName: {
display: 'long_name',
type: 'route'
},
cityName: {
display: 'long_name',
type: 'locality'
},
stateName: {
display: 'short_name',
type: 'administrative_area_level_1'
},
zipCode: {
display: 'short_name',
type: 'postal_code'
}
};
var autocomplete;
var autocompleteOptions = {
radius: 10,
types: ['geocode']
};
function initAutocomplete() {
autocomplete = new google.maps.places.Autocomplete($inputAuto[0], autocompleteOptions);
autocomplete.addListener('place_changed', setAddress);
};
function setAddress() {
var place = autocomplete.getPlace().address_components;
var streetAddr = [addrComponents.streetNumber, addrComponents.streetName];
var streetAddrDisplay = [];
// Add additional field values
place.forEach(function(placeComponent) {
streetAddr.forEach(function(streetAddrComponent) {
if (placeComponent.types[0] === streetAddrComponent.type) {
streetAddrDisplay.push(placeComponent[streetAddrComponent.display]);
}
// else if <additional field values>
});
});
var addrString = streetAddrDisplay.join(' ');
$inputAuto.val(addrString);
};
initAutocomplete();
}());
autocomplete.getPlace()
returns an object with a bunchof stuff that you can use for other Maps API calls. However, you just want the first object within that, address_components
. This is an array of matched address component objects. Each of these objects has a long_name
and short_name
that you'll use to populate your inputs. Each object also includes an array of types
that indicates what the strings represent (the 0 index is the unique identity of the object). In your case: street number (street_number
), street name (route
), city (locality
), county (administrative_area_level_2
), state (administrative_area_level_1
), country (country
), and zip (postal_code
).
autocomplete.getPlace()
返回一个包含一堆东西的对象,您可以将其用于其他 Maps API 调用。但是,您只需要其中的第一个对象,address_components
. 这是一组匹配的地址组件对象。这些对象中的每一个都有一个long_name
和short_name
,您将使用它来填充您的输入。每个对象还包括一个数组,types
该数组指示字符串代表什么(0 索引是对象的唯一标识)。在您的情况下:街道号码 ( street_number
)、街道名称 ( route
)、城市 ( locality
)、县 ( administrative_area_level_2
)、州 ( administrative_area_level_1
)、国家 ( country
) 和邮编 ( postal_code
)。
In this example, the addrComponents
object contains easily-readable options for matching items in the place
array. In order to achieve your desired result of populating multiple fields, you just need to select the fields and set their contents with $inputName.val(desiredString)
.
在此示例中,addrComponents
对象包含用于匹配place
数组中项目的易于阅读的选项。为了实现填充多个字段的理想结果,您只需选择字段并使用$inputName.val(desiredString)
.
As an additional reference, the Google Maps JavaScript API docscontain an exampleof exactly what you want to do.
作为额外的参考,Google Maps JavaScript API 文档包含您想要做什么的示例。
Hope that helps. Good luck!
希望有帮助。祝你好运!
回答by brassmookie
The simplest way I've found to programmatically change the value of an Autocomplete input is to reinitialize the input field.
我发现以编程方式更改自动完成输入值的最简单方法是重新初始化输入字段。
var input = document.getElementById(input_auto);
autocomplete = new google.maps.places.Autocomplete(input, option);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// perform any functions based on place input
...
// change the value of your autocomplete to whatever you want
input.value = 'yyy';
// reinitialize with new input value
autocomplete = new google.maps.places.Autocomplete(input, option);
}
回答by Nicholas Ryan Bowers
You can fix this by adding event listeners to blur
and keydown
events to override the automatic value. Check out what I did below:
您可以通过添加事件侦听器blur
和keydown
事件来覆盖自动值来解决此问题。看看我在下面做了什么:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Places search box</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
$(function(){
var input_auto = document.getElementById('input_auto');
autocomplete = new google.maps.places.Autocomplete(input_auto,{types: ['geocode'],radius: 10});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
input_auto.addEventListener('blur', function() {
input_auto.value = 'yyy';
});
input_auto.addEventListener('keydown', function() {
input_auto.value = 'yyy';
});
setTimeout(function(){$('#input_auto').val('yyy');},1);
});
});
</script>
</head>
<body>
<input id="input_auto" type="text">
</body>
</html>
You can optionally add setTimeouts if you run into any problems.
如果遇到任何问题,您可以选择添加 setTimeouts。