You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Places API:Place ID转地名的Google Sheets实现需求

解决Google Sheets中Place ID转地名的问题

自定义函数实现Place ID反向地理编码

你可以通过Google Apps Script编写自定义函数,调用Google Maps地理编码服务将Place ID转换为对应的可读地名。以下是具体实现:

1. 编写反向地理编码函数

打开Google Sheets,点击「扩展程序」>「Apps Script」,将以下代码粘贴到脚本编辑器中:

function GetPlaceNameFromID(placeId) {
  if (!placeId) return "";
  try {
    const geocoder = Maps.newGeocoder();
    const response = geocoder.reverseGeocode({ placeId: placeId });
    
    if (response.results.length === 0) return "未找到对应地名";
    
    // 默认返回完整格式化地址,可根据需求修改为特定层级名称
    return response.results[0].formatted_address;
    
    // 示例:仅返回城市名称(locality类型)
    // const components = response.results[0].address_components;
    // for (const comp of components) {
    //   if (comp.types.includes('locality')) {
    //     return comp.long_name;
    //   }
    // }
    // return response.results[0].formatted_address; // 无匹配时返回完整地址
  } catch (error) {
    return `错误: ${error.message}`;
  }
}

2. 在单元格中使用函数

保存脚本后回到Google Sheets,在需要显示地名的单元格中输入:

=GetPlaceNameFromID(A1)

将A1替换为存放Place ID的单元格地址即可自动转换为对应地名。

3. 整合到现有函数(可选)

如果你想让原有的LookupRegionByName直接返回地名而非Place ID,可以修改函数如下:

function LookupRegionByName(regionName) {
  if (!regionName) return "";
  try {
    const geocoder = Maps.newGeocoder();
    const response = geocoder.geocode(regionName);
    
    if (response.results.length === 0) return "未找到匹配区域";
    
    // 直接返回格式化地址,替代Place ID输出
    return response.results[0].formatted_address;
  } catch (error) {
    return `错误: ${error.message}`;
  }
}

注意事项

  • 权限授权:第一次运行自定义函数时,需要按照提示完成授权(选择「高级」>「前往XX脚本」)。
  • 配额限制:Google Apps Script的Maps服务有每日调用配额,高频使用可能触发限制,若需更高配额可考虑使用付费的Google Maps API并修改代码调用HTTP接口。
  • 自定义地名层级:如果需要特定类型的地名(如省份、国家、街道),可修改代码中address_components的判断逻辑,对应类型参考Google Maps地理编码文档的地址组件类型定义。

内容的提问来源于stack exchange,提问作者Michael T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:15:59