当选择自动填充列表时,我有以下代码来解析国家/地区:
$('#spot_address').autocomplete({ // This bit uses the geocoder to fetch address values source: function(request,response) { geocoder.geocode( {'address': request.term },function(results,status) { // Get address_components for (var i = 0; i < results[0].address_components.length; i++) { var addr = results[0].address_components[i]; var getCountry; if (addr.types[0] == 'country') getCountry = addr.long_name; } response($.map(results,function(item) { return { label: item.formatted_address,value: item.formatted_address,latitude: item.geometry.location.lat(),longitude: item.geometry.location.lng(),country: getCountry } })); }) },// This bit is executed upon selection of an address select: function(event,ui) { // Get values $('#spot_country').val(ui.item.country); $('#spot_lat').val(ui.item.latitude); $('#spot_lng').val(ui.item.longitude); var location = new google.maps.LatLng(ui.item.latitude,ui.item.longitude); marker.setPosition(location); map.setCenter(location); },// Changes the current marker when autocomplete dropdown list is focused focus: function(event,ui) { var location = new google.maps.LatLng(ui.item.latitude,ui.item.longitude); marker.setPosition(location); map.setCenter(location); } });
然而,上面的代码不起作用,当国家被解析时,只有自动完成的第一个结果被解析,无论数据结果[0]是什么,因为它只获取第一个结果.
我试图将它移动到选择功能,但是在选择中的ui只包含格式化地址,经度和纬度,但不包含address_components.
选择自动填写列表项目时,请务必发送正确的国家/地区?
非常感谢.
解决方法
一般解决方案:
var address_components = results[0].address_components; var components={}; jQuery.each(address_components,function(k,v1) {jQuery.each(v1.types,function(k2,v2){components[v2]=v1.long_name});})
现在你的组件看起来像这样:
street_number: "1100",route: "E Hector St",locality: "Conshohocken",political: "United States",administrative_area_level_3: "Whitemarsh"… administrative_area_level_1: "Pennsylvania" administrative_area_level_2: "Montgomery" administrative_area_level_3: "Whitemarsh" country: "United States" locality: "Conshohocken" political: "United States" postal_code: "19428" route: "E Hector St" street_number: "1100"
你可以这样查询:
components.country