Fla*_*nix 1 javascript jquery google-maps-api-3
我有谷歌地图自动完成功能,可以使用以下几个input标签:
<input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />
Run Code Online (Sandbox Code Playgroud)
要启用Google地图自动完成功能,我需要以下代码:
//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();
});
});
Run Code Online (Sandbox Code Playgroud)
然后,在MyFunc()功能中我做我需要的:
function MyFunc() {
var fullAddress = autocomplete.getPlace().formatted_address;
var input = $(this);
//stuff that uses input
}
Run Code Online (Sandbox Code Playgroud)
但是,这段代码有两个问题:
$(this)但它没有工作.jQuery如何帮助我?提前致谢!
你真的不需要jQuery.这是一个仅使用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>
Run Code Online (Sandbox Code Playgroud)
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);
});
}
Run Code Online (Sandbox Code Playgroud)
如果你想用jQuery做,那么你可以尝试这种方式:
$('.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);
});
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
1511 次 |
| 最近记录: |