Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  123] [ 7]  / answers: 1 / hits: 38580  / 15 Years ago, wed, july 15, 2009, 12:00:00

I'm using the Google Map API to retrieve city + state/region information from a postal code lookup. The issue is that in some cases a postal code lookup won't retrieve a city name. An example is 92625 (U.S).



var g = new GClientGeocoder();
g.setBaseCountryCode('US');
g.getLocations('92625', function(response){
if (response) {
var place = response.Placemark[0];
var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
GLog.write(City = +city+ : State/Region = +state+ : Country = + g.getBaseCountryCode());
}
});


In certain cases, as mentioned above, there won't be a city name in the result so there will be an undefined error for city, because the key Locality does not exist. This error prevents the rest of the script from running.



I was able to remedy it by...



    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null)
var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
else
var city = '';


...but this has me paranoid about a similar error for other keys. Eg: If AdministrativeArea is undefined the above IF statement would also cause an undefined error. So should I be checking to see if every Key/Node exists? Seems to be a messy approach because some of these keys are 5+ levels deep...is there an easier way to go about it, maybe some JQuery method I'm not familiar with?


More From » json

 Answers
8

Alternatively, you could make a function, that gives you defaults:



function valueOrDefault(val, def) {
if (def == undefined) def = ;
return val == undefined ? def : val;
}


And then use it like this:



var place = response.Placemark[0];
var state = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
var city = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);


Personally, I think it's a little nicer to write, than p00ya's proposal, although it's a little hacky fiddling around in undefined objects ... one could maybe change it to this:



function drill(p, a) {
a = a.split(.);//add this
for (i in a) {
var key = a[i];
if (p[key] == null)
return '';
p = p[key];
}
return p;
}
var obj = {foo:{bar:{baz:quux}}};
var s = drill(obj, foo.bar.baz));//and you can use a simple property chain

[#99123] Friday, July 10, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makenatiffanic

Total Points: 412
Total Questions: 106
Total Answers: 90

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
;