jQuery和谷歌地图自动完成

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)

但是,这段代码有两个问题:

  • 第一个是我使用Id,影响多个输入框(我有很多输入字段).我尝试按类选择,但它失败并显示错误'undefined'.如何将该函数应用于输入字段集合?
  • 我如何知道点击了哪个字段?我尝试使用jquery,$(this)但它没有工作.jQuery如何帮助我?

提前致谢!

MrU*_*own 9

你真的不需要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)

JSFiddle demo

如果你想用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)

JSFiddle demo

希望这可以帮助.