【问题标题】:JSON result get country from address_componentsJSON 结果从 address_components 获取国家
【发布时间】:2014-03-10 18:40:56
【问题描述】:

您好 JSON 新手,我想知道是否可以从此 API 的 JSON 结果中调用“国家”:http://maps.google.com/maps/api/js?sensor=true&libraries=places

我尝试使用循环来获取 JSON 结果 address_components 的最后一部分,但我意识到“国家”的位置因用户输入而异

详细说明:
场景一: 用户输入:
736 Lockhart Court, Harristown QLD 4350, 澳大利亚

结果:
澳大利亚//这是正确的

场景 2: 用户输入:
美国弗吉尼亚州汉普顿兰利空军基地

结果:
弗吉尼亚//不正确

我当前的代码获取数组 address_components 的最后一个索引,我想知道我是否可以这样做 *data.results[0].address_components[country].long_name;*,但我只是不知道正确的方法。

代码:

<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 索引的情况下获取特定(国家、街道号码等)元素?

【问题讨论】:

    标签: javascript json html


    【解决方案1】:

    在您的情况下,您将不得不手动迭代数组并检查types 数组是否包含'country'。您可以为此使用array.indexof

    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;
              }
        }
    }
    

    【讨论】:

      【解决方案2】:

      使用 ES6 的更新答案

      data.results[0].address_components.forEach(_item => {
        if (_item.types.indexOf('country') !== -1) {
           document.getElementById('res').value = _item.short_name;
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 2012-06-20
        • 2018-01-16
        相关资源
        最近更新 更多