JSON结果从address_components获取国家 [英] JSON result get country from address_components
问题描述
您是JSON的新手,我想知道是否可以从此API的JSON结果中调用国家/地区":
Hi new to JSON and I was wondering if I can call the "country" from this API's JSON result: http://maps.google.com/maps/api/js?sensor=true&libraries=places
我尝试使用一个获取JSON结果address_components的最后一部分的循环,但我意识到国家/地区"的位置因用户输入而异
I tried to use a loop that gets the last part of the JSON result address_components but I realized that the location of the "country" varies from the user's input
详细说明:
方案1:
用户输入:
736 Lockhart Court,Harristown QLD 4350,澳大利亚
To elaborate:
Scenario 1:
USER's INPUT:
736 Lockhart Court, Harristown QLD 4350, Australia
结果:
澳大利亚//这是正确的
Result:
Australia //this is correct
方案2:
用户输入:
美国弗吉尼亚州汉普顿的兰利空军基地
Scenario 2:
USER's INPUT:
Langley Air Force Base, Hampton, VA, United States
结果:
弗吉尼亚////不正确
Result:
Virginia //not correct
我当前的代码获取了address_components数组的最后一个索引,我想知道是否可以做这样的事情 * data.results [0] .address_components [country] .long_name; * ,但我只是不知道正确的方法.
My current code gets the last index of the array address_components and I am wondering if I can just do something like this *data.results[0].address_components[country].long_name;*, but I just don't know the proper way.
代码:
<html>
<head></head>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn1 ").click(function() {
var address=encodeURI($('#userInput').val());
var url='https://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=true';
$.getJSON(url, function(data){
for(var row=0; row<data.results.length;row++){
document.getElementById('res').value = (data.results[row].address_components[data.results[row].address_components.length-2].long_name);
}
});
});
});
</script>
<body>
<input type="text" id="res">
<input type="text" name="userInput" id="userInput" />
<input type="button" id="btn1" value="Load Data" />
</body>
</html>
如何在不依赖address_components索引的情况下获取特定的(国家/地区,街道编号等)元素?
How can I get a specific(country,street number etc) element without relying on the address_components index?
推荐答案
在您的情况下,您将必须手动迭代数组并检查types
数组是否包含'country'
.您可以将 array.indexof 用于这个.
in your case you will have to manually iterate the array and check that the types
array contains 'country'
. You can use array.indexof for this.
for(var row=0; row<data.results.length;row++){
var item = data.results[row];
for( var i = 0; i< item.address_components.length; i++) {
var component = item.address_components[i];
if( component.types.indexof('country') != -1) {
document.getElementById('res').value = component.long_name;
}
}
}
这篇关于JSON结果从address_components获取国家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!