Javascript 如何从Google Maps Geocoder API获取邮政编码
我需要使用Google Maps Geocoder API从给定地址获取邮政编码。我已经能够获得其他数据,例如经度和纬度,但是获得邮政编码只是有点不同。我试图从中解析邮政编码的Json是:Javascript 如何从Google Maps Geocoder API获取邮政编码,javascript,json,google-maps,Javascript,Json,Google Maps,我需要使用Google Maps Geocoder API从给定地址获取邮政编码。我已经能够获得其他数据,例如经度和纬度,但是获得邮政编码只是有点不同。我试图从中解析邮政编码的Json是: { "results" : [ { "address_components" : [ { "long_name" : "1600",
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4267861,
"lng" : -122.0806032
},
我编写的javascript函数是:
async function getZipCode() {
const searchedAddress = @Html.Raw(Json.Serialize(ViewData["searchString"]));
const response = await axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: searchedAddress,
key: [key],
sensor: 'true_or_false'
}
})
let addressComponents = response.data.results[0].address_components;
for (var i = 0; i < addressComponents.count; i++) {
if (addressComponents[i].types == 'postal_code') {
let zip = response.data.results[0].address_components[i].short_name;
return zip;
console.log(zip);
}
}
}
但情况并非总是如此。有时,邮政编码包含在地址组件的不同迭代中,因此我需要想出一种方法来检查类型,然后获取简短的名称
我的功能是不向控制台返回任何内容。我意识到console.log语句在“if”语句中,但在如何实际获取这些数据方面,我还是一片空白。您的尝试非常接近。你似乎出了差错的地方是:
if (addressComponents[i].types == 'postal_code') { // ...
当我们知道类型
似乎总是一个数组时,您要求解释器计算的是地址组件[i].types
是否等于字符串邮政编码
。在大多数设置中,数组不能直接强制为字符串
实际上,您要确定的是数组中是否存在字符串邮政编码。因此,您可以使用:
旁白:在返回之后的任何内容都不会被执行,因此无论成功与否,您都不会看到console.log(zip)
在任何情况下使用您的代码的输出。使用带有实心语法突出显示的IDE可能会提醒您注意这一点,因为它显示的代码不会以较低的透明度执行-如果您还没有开始使用IDE,我建议您立即开始使用。非常感谢。这与将addressComponents.count更改为addressComponents.length一起起到了作用
if (addressComponents[i].types == 'postal_code') { // ...
if (addressComponents[i].types.includes('postal_code')) { // process the postal code data