我正在使用Google地图API从邮政编码查询中检索城市+州/区域信息。问题在于,有些情况下邮政编码查询无法检索到城市名称。例如92625(美国)。
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());
}
});
如上所述,在某些情况下,结果中将没有城市名称,因此city变量报undefined错误,因为键“Locality”不存在。这个错误会阻止脚本的其余部分运行。
我通过...来解决这个问题。
if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null)
var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
else
var city = '';
...但这让我担心其他键也会出现类似的错误。例如:如果AdministrativeArea未定义,则上述IF语句也会导致未定义的错误。所以我应该检查每个Key/Node是否存在吗?这似乎是一种麻烦的方法,因为其中一些键深度达到了5级以上...是否有更简单的方法去处理它,也许有一些我不熟悉的jQuery方法?