【发布时间】:2021-06-08 00:44:54
【问题描述】:
我需要使用 Google Maps Geocoder API 从给定地址获取邮政编码。我已经能够获取其他数据,例如经度和纬度,但是获取邮政编码只是有点不同。我试图从中解析邮政编码的 Json 是:
{
"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);
}
}
}
我知道,对于这个json示例中提供的数据,我可以通过
response.data.results[0].address_components[6].short_name;
但情况并非总是如此。有时邮政编码包含在 address_components 的不同迭代中,所以我需要想出一种方法来检查类型,然后获取 short_name。
我拥有的功能没有向控制台返回任何内容。我意识到console.log 语句在“if”语句中,但是对于如何实际获取这些数据却一无所知。
【问题讨论】:
标签: javascript json google-maps