gpt4 book ai didi

javascript - 在自动完成选择时解析谷歌地图中的 address_components

转载 作者:可可西里 更新时间:2023-11-01 01:44:43 26 4
gpt4 key购买 nike

我有以下代码来解析 country 选择“自动完成”列表时:

$('#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);
}
});

但是,上面的代码不起作用,在解析国家时,无论如何只解析自动完成的第一个结果,这对数组results[0]有意义因为它只获取第一个结果。

我试图将它移动到select函数中,但是select中的ui只包含formatted_addresslongitudelatitude,但不是 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

关于javascript - 在自动完成选择时解析谷歌地图中的 address_components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com