JSON result get country from address_components

烂漫一生 提交于 2021-02-15 07:34:27

问题


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

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

To elaborate:
Scenario 1: USER's INPUT:
736 Lockhart Court, Harristown QLD 4350, Australia

Result:
Australia //this is correct

Scenario 2: USER's INPUT:
Langley Air Force Base, Hampton, VA, United States

Result:
Virginia //not correct

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.

Code:

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

How can I get a specific(country,street number etc) element without relying on the address_components index?


回答1:


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


来源:https://stackoverflow.com/questions/21727931/json-result-get-country-from-address-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!