2011-08-22 128 views
1

我试图通过添加国名的提取来扩展这个website的谷歌地图标记示例。调用JavaScript函数的正确方法

由于谷歌地图返回一个数组,每个地址都有详细信息,所以我需要遍历数组以查找条目,例如为“国家”。由于我想重复使用这段代码,我创建了一个函数。

但我不知道如何调用这个函数(这里调用找到(组件,项目))正确。

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

谢谢你的想法和建议!在autocomplete选项对象

$(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); 
    } 
    }); 
}); 
+0

为什么你有嵌套的文档就绪功能? (你已经得到'$(document).ready(function(){',然后两行后面的等价语句'$(function(){') – nnnnnn

回答

0

find()函数被定义。

如果你想访问你的查找功能,你必须定义它的自动完成选项之外,或者得到一个指向它:

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

这是因为jQuery改变功能的情况下与元素这是附加到听众。

+0

)谢谢,我把函数移到了自动完成函数之外按你写的方式工作,谢谢你的提示! – neurix

相关问题