2014-10-28 39 views
0

我正在使用Google表格函数来反转地理编码列表纬度/经度坐标。它看起来像这样:
为什么Google表格无法从Maps API中找到reverseGeocode方法?

function getAdd(lat, lng) { 
if (lat == "") { 
return "You have to provide latitudinal coordinates to the place" 
} if (lng == ""){ 
return "You have to provide longitudinal coordinates to the place" 
} 

var response = Maps.newGeocoder().reverseGeocode(lat, lng); 
for (var i = 0; i < response.results.length; i++) { 
var result = response.results[i]; 

Utilities.sleep(1000); 

return result.formatted_address; 

} 

}; 

问题1:为什么谷歌表给我下面的错误:“找不到方法reverseGeocode(对象(类))”?

问题2:一旦我解决了这个问题,如何从结果数组中获取国家名称而不是结果中的完整地址呢?

回答

0

您试图为响应对象中的每个结果返回一个结果。相反,你必须选择一个:

function getAdd(lat, lng) { 
    if (lat == "") { 
    return "You have to provide latitudinal coordinates to the place" 
    } if (lng == ""){ 
    return "You have to provide longitudinal coordinates to the place" 
    } 
    var response = Maps.newGeocoder().reverseGeocode(lat, lng); 
    return response.results[0].formatted_address; 
}; 

如果你正在寻找的只是国家,结果对象的格式是在这里: https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding

在这种情况下,你应该遍历这些结果[ 0]对象并测试以查看这些类型是否包含“国家/地区”。如果有,请选择结果[0] .address_components [i] .short_name,其中我是您的迭代器。或者改用long_name。

+0

感谢,尽管代码与在此之前,甚至工作,我仍然得到一个“无法找到方法”的错误。 – 2014-10-28 22:24:22

+0

我无法解释为什么它以前工作。如果您遇到无法找到方法错误,则可能是您设置项目的方式存在问题。我测试了这个代码,它工作。我测试了你的代码,它没有,但没有给我一个无法找到错误。 – 2014-10-28 23:11:40

0

好吧,算出来。下面是我最终得到了国家从经/纬:

function getAdd(lat, lng) { 
    if (lat == "") { 
     return "Insert latitude." 
    } 
    if (lng == ""){ 
     return "Insert longitude." 
    } 

var response = Maps.newGeocoder().reverseGeocode(lat,lng); 

Utilities.sleep(1000); //in order not to exeed api calls per second 

for (var i in response.results) { 
    var result = response.results[i]; 
} 

for (var j in result.address_components) { 
    for (var k in result.address_components[j].types) { 
     if (result.address_components[j].types[k] == "country") { 
      return result.address_components[j].long_name;  
     } 
    } 
} 

}; 
相关问题