1

我正在尝试通过添加国家名称的提取来扩展本网站的谷歌地图标记示例。

由于谷歌地图返回一个包含每个地址详细信息的数组,我需要遍历该数组以找到例如“国家”的条目。由于我想重用这段代码,我创建了一个函数。

但我不确定如何正确调用这个函数(这里调用find(components, item))。

我没有从 find 函数中得到任何回报。如何从 select 函数中正确调用 find 函数? *为什么我得到一个空的回报可能有不同的错误吗?*

感谢您的想法和建议!

$(document).ready(function() { 

initialize();

$(function() {
    $("#address").autocomplete({
        //This bit uses the geocoder to fetch address values
        source: function(request, response) {
            geocoder.geocode( {'address': request.term }, function(results, status) {
                response($.map(results, function(item) {
                    return {
                        label:  item.formatted_address,
                    value: item.formatted_address,
                    components: item.address_components,
                    latitude: item.geometry.location.lat(),
                    longitude: item.geometry.location.lng()
                    }
                }));
            })
        },

        // address_component selection
        find: function(components, item) {
            for(var j=0;j < components.length; j++){
                for(var k=0; k < components[j].types.length; k++){
                    if(components[j].types[k] == "country"){
                        return components[j].long_name;
                    }
                }
            }
        },

    //This bit is executed upon selection of an address
    select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        $("#country").val(this.find(ui.item.components, "country"));
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
    }
    });
});
4

1 回答 1

0

find()函数在autocomplete选项对象中定义。

如果您想访问您的查找功能,您必须在自动完成选项之外定义它或获取指向它的指针:

var find = $(event.target).data("autocomplete").options.find;

这是因为 jQuery 使用附加到侦听器的元素更改函数的上下文。

于 2011-08-22T01:38:11.127 回答