Mr. Fox Mr. Fox - 1 year ago 54
JSON Question

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?

Answer Source

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