Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

javascript - JSON result get country from address_components

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...