gpt4 book ai didi

javascript - 使用 jQuery 根据 Google Geocoding API JSON 响应的类型获取值

转载 作者:行者123 更新时间:2023-11-28 14:53:06 25 4
gpt4 key购买 nike

我正在从 Google Geocoding API 获取 JSON 响应

其格式是这样的:

{
"results" : [
{
"address_components" : [
{
"long_name" : "Department of Information science and engineering",
"short_name" : "Department of Information science and engineering",
"types" : [ "premise" ]
},
{
"long_name" : "Gokul",
"short_name" : "Gokul",
"types" : [ "political", "sublocality", "sublocality_level_1" ]
},
{
"long_name" : "Hubballi",
"short_name" : "Hubballi",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Dharwad",
"short_name" : "Dharwad",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Karnataka",
"short_name" : "KA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "580030",
"short_name" : "580030",
"types" : [ "postal_code" ]
}

现在我可以使用 JavaScript 获取属性

"Postal Code:" + json.results[0].address_components[6].long_name

但根据我的研究,我发现 address_components[6] 可能并不总是相同的数据。所以我想根据类型获取值,以便我始终获得正确的数据。

现在我找到了一种使用 php 来做到这一点的方法:

foreach ($jsondata["results"] as $result) {
foreach ($result["address_components"] as $address) {
if (in_array("sublocality", $address["types"])) {
$city = $address["long_name"];
}
}
}

但我无法弄清楚如何迭代每个结果并根据 JavaScript/JQuery 中的类型获取值。

谁能告诉我它是如何完成的?

最佳答案

您可以使用下面给出的代码(纯 JavaScript)来实现与使用 PHP 实现的功能相同的功能。运行代码片段以查看输出。

var results = [{
"address_components": [{
"long_name": "Department of Information science and engineering",
"short_name": "Department of Information science and engineering",
"types": ["premise"]
}, {
"long_name": "Gokul",
"short_name": "Gokul",
"types": ["political", "sublocality", "sublocality_level_1"]
}, {
"long_name": "Hubballi",
"short_name": "Hubballi",
"types": ["locality", "political"]
}, {
"long_name": "Dharwad",
"short_name": "Dharwad",
"types": ["administrative_area_level_2", "political"]
}, {
"long_name": "Karnataka",
"short_name": "KA",
"types": ["administrative_area_level_1", "political"]
}, {
"long_name": "India",
"short_name": "IN",
"types": ["country", "political"]
}, {
"long_name": "580030",
"short_name": "580030",
"types": ["postal_code"]
}]
}];

for (result of results) {
for (address of result.address_components) {
if (address.types.indexOf("sublocality") != -1) {
var city = address.long_name;
alert(city);
}
}
}

关于javascript - 使用 jQuery 根据 Google Geocoding API JSON 响应的类型获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43844541/

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