0

I am trying to read JSON information (https://maps.googleapis.com/maps/api/geocode/json?address=Mountain+View+Amphitheatre+Parkway&sensor=false) from JavaScript using:

$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address="+city+"+"+steet+"&sensor=false", function(json) {
if (json.status == 'ZERO_RESULTS'){
    alert('Wrong input');
}
else{
// Here I would like to read json.results.geometry.location.lat 
}

});

But it does not work. If I try to read json.results, I get [object Object]. Because printing json gave me the same I thought I could just continue with periods, but it did not work.

After that I tried to iterate over json.results and after to parse the object to an array, but all did not work.

2
  • 2
    What did you actually do when you say "If I try to read json.results". I'm guessing you tried to alert() it? If that is the case, don't; alert() isn't suitable for debugging, use console.log() instead. Commented Jan 30, 2013 at 15:48
  • 1
    Not sure I understand your question, but does this help? jsfiddle.net/ExplosionPIlls/RmbTD/1 Commented Jan 30, 2013 at 15:48

3 Answers 3

2

results is an array of objects. So you should try:

json.results[0].geometry.location.lat
Sign up to request clarification or add additional context in comments.

Comments

1

json.results is an Array, you have to access the Elements inside it.

The code you have, as is, is trying to access the property location of the object geometry.

But since json.results is an Array, json.results.geometry is undefined and therefore cannot have a property.

If you would check the Errors in the console, you should get something like

Uncaught TypeError: Cannot read property 'location' of undefined

What you want is accessing the Elements of the results Array, as each Element in it represents one search result of gMaps, which then holds the information you want to access.

e.g. json.results[0] would give you the Object representing the first search result, json.results[1] would give you the second, and so on.

So if you change it to

$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=Berlin+Alexanderplatz&sensor=false", function(json) {
if (json.status == 'ZERO_RESULTS'){
    alert('Wrong input');
}
else{
  console.log(json.results[0].geometry.location.lat) // 52.5218316
}

});

You get the Latitude of the first result, just as you intended to.

Here's a JSBin.

Comments

0

results is an array where you should loop over:

for (var i = 0; i < json.results.length; i++) {
     console.log(json.results[i].geometry.location.lat);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.