jQuery 和 google 地图自动完成

jQuery and google maps auto complete

我有 Google 地图自动完成处理几个 input 标签,如下所示:

 <input class="controls pac-input" id="pac-input" type="text" onfocus="geolocate()" placeholder="Type custom address" />

要启用 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();
    });

});

然后,在 MyFunc() 函数中执行我需要的操作:

function MyFunc() {
    var fullAddress = autocomplete.getPlace().formatted_address;
    var input = $(this);
    //stuff that uses input
}

然而,这段代码有两个问题:

提前致谢!

为了查明正在调用哪个输入元素,您可以将事件传递给 MyFunc()。使用 $(this) 不会在该函数外部检查调用它的内容。

addListener 更新为以下内容。

google.maps.event.addListener(autocomplete, 'place_changed', function (e) {
    MyFunc(e);
});`

并将MyFunc()更新为

function MyFunc(e) {
    var fullAddress = autocomplete.getPlace().formatted_address;
    var input = e;
    //stuff that uses input
}

然后您可以使用 input 作为保存有关正在更新的元素的信息的变量。如果您在 var input = e; 下方执行 console.log(input);,您将看到可用于获取数据的项目列表。

您可能最感兴趣的是将 var input = e; 设置为 var input = e.target;。这将使您可以轻松获取有关输入的信息。

示例:input.value 将 return 相关输入的值。

不需要 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>

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);
    });
}

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);
    });
});

JSFiddle demo

希望对您有所帮助。