Michael
Michael

Reputation: 3

Google Maps API V3 geocode javascript if json value exists

I am somewhat a novice with Javascript and I am trying to create a very simple if statement.

I am sending an address to the google geocoder and receiving the json result. I'm parsing the result and printing into my html document.

I now only want to attempt to print values that actually exist to keep from crashing my code.

right now I have:

document.getElementById('lat').innerHTML = [results[1].geometry.location.lat()];

and it works, but I don't want that line to run if "results[1].geometry.location.lat()" doesn't exist in the json result.

I have tried:

if ([results[1].geometry.location.lat()] != null) {
    document.getElementById('lat').innerHTML = [results[1].geometry.location.lat()];    
}

but the line still runs even if there is no value there. I gotta be doing this wrong. Please help someone.

Because the value will be different every time, I just want the line to run if there is ANY value.

Upvotes: 0

Views: 1180

Answers (2)

awm
awm

Reputation: 6570

[results[1].geometry.location.lat()] is shorthand for an array; it will never be null.

Take out the [].

The truly safe way to test would be:

if (results[1] && results[1].geometry && results[1].geometry.location && results[1].geometry.location.lat) {
   ...

Upvotes: 1

Bemmu
Bemmu

Reputation: 18217

If you know that geometry exists but you are unsure if location exists or not, you can check against undefined.

if (results[0].geometry.location !== undefined) {
    var lat = results[0].geometry.location.lat();
}

If you don't know if even geomery exists, then you would also need to check if that is undefined.

Upvotes: 0

Related Questions