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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…