jQuery和Google地图自动完成 [英] jQuery and google maps auto complete
本文介绍了jQuery和Google地图自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我让Google Maps自动完成功能像这样处理几个input
标记:
I have Google Maps Autocomplete working on severalinput
tags like this:
<input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />
要启用Google Maps自动完成功能,我需要以下代码:
To enable Google Maps auto-complete, I have the following code:
//https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
$(document).ready(function () {
autocomplete = new google.maps.places.Autocomplete((document.getElementById('pac-input')), { types: ['geocode'] });
google.maps.event.addListener(autocomplete, 'place_changed', function () {
MyFunc();
});
});
然后,在MyFunc()
函数中,我需要执行以下操作:
And then, in the MyFunc()
function I do what I need:
function MyFunc() {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = $(this);
//stuff that uses input
}
但是此代码有两个问题:
This code however, has two problems:
- 首先是我正在使用一个ID来影响多个输入框(我有很多输入字段).我尝试按类别选择,但失败,并显示错误未定义".如何将该功能应用于输入字段的集合?
- 我如何知道要单击哪个字段?我尝试使用jquery
$(this)
,但它不能正常工作. jQuery如何帮助我?
- The first is that i am using an Id, to affect multiple input boxes (I have many input fields). I tried selecting by class but it fails with error ´undefined´. How can I apply that function to a collection of input fields?
- How do I know which field is being clicked? I tried using the jquery
$(this)
but it aint working. How can jQuery help me ?
提前谢谢!
推荐答案
您实际上不需要jQuery.这是一个仅使用javascript的工作示例:
You don't really need jQuery for this. Here is a working example using only javascript:
HTML:
<input class="autocomplete" id="ac1" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac2" placeholder="Enter your address" type="text"></input>
<input class="autocomplete" id="ac3" placeholder="Enter your address" type="text"></input>
JavaScript:
JavaScript:
var acInputs = document.getElementsByClassName("autocomplete");
for (var i = 0; i < acInputs.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(acInputs[i]);
autocomplete.inputId = acInputs[i].id;
google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
}
如果要使用jQuery,可以尝试以下方法:
If you want to do it with jQuery then you can try this way:
$('.autocomplete').each(function() {
var autocomplete = new google.maps.places.Autocomplete($(this)[0]);
autocomplete.inputId = $(this).attr('id');
google.maps.event.addListener(autocomplete, 'place_changed', function () {
console.log('You used input with id ' + this.inputId);
});
});
希望这会有所帮助.
这篇关于jQuery和Google地图自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文