我使用以下内容从地理编码中获取lat-lng ..
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
如何从...中提取邮政编码
{
"status": "OK",
"results": [ {
"types": [ "street_address" ],
"formatted_address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
}, {
"long_name": "Amphitheatre Pkwy",
"short_name": "Amphitheatre Pkwy",
"types": [ "route" ]
}, {
"long_name": "Mountain View",
"short_name": "Mountain View",
"types": [ "locality", "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" ]
} ],
"geometry": {
"location": {
"lat": 37.4219720,
"lng": -122.0841430
},
"location_type": "ROOFTOP",
"viewport": {
"southwest": {
"lat": 37.4188244,
"lng": -122.0872906
},
"northeast": {
"lat": 37.4251196,
"lng": -122.0809954
}
}
}
} ]
}
答案 0 :(得分:13)
您可以使用以下函数来提取任何地址组件:
function extractFromAdress(components, type){
for (var i=0; i<components.length; i++)
for (var j=0; j<components[i].types.length; j++)
if (components[i].types[j]==type) return components[i].long_name;
return "";
}
要提取您致电的邮政编码:
extractFromAdress(results[0].address_components, "postal_code");
但你也可以获得其他有趣的信息:
extractFromAdress(results[0].address_components, "route");
extractFromAdress(results[0].address_components, "locality");
extractFromAdress(results[0].address_components, "country");
等...
答案 1 :(得分:0)
我说你需要循环results.address_components
。在每次迭代时检查types数组是否包含“postal_code”。如果是这样,将其保存到变量,也可能会脱离循环。虽然可能值得研究一下postal_code是否总是在address_component [5]中,这样可以省去你的循环。