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

Google Maps地理编码API坐标转城市功能异常求助

解决Google Maps逆地理编码获取城市的问题

原代码存在几个导致输出不符合预期的问题:

  • 循环中遇到administrative_area_level_1(通常为省/州级)会直接返回,不会继续查找更精确的locality(城市级),若该类型在locality之前出现,会返回错误层级的结果
  • 仅依赖HTTP状态码判断请求成功,未检查API返回的status字段,可能忽略无结果、配额超限等API层面的失败情况
  • 未覆盖部分地区的城市对应类型(比如部分地区用postal_town或administrative_area_level_2表示城市)

下面是修正后的代码:

import requests

def get_city(latitude, longitude, api_key):
    """通过Google Maps Geocoding API从坐标获取城市名称"""
    url = f"https://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&key={api_key}"
    response = requests.get(url)
    
    if response.status_code == 200:
        result_data = response.json()
        if result_data.get('status') == 'OK':
            results = result_data.get('results', [])
            if results:
                city = None
                admin_level_1 = None
                # 遍历所有地址组件,按优先级收集目标值
                for component in results[0]['address_components']:
                    types = component['types']
                    if 'locality' in types:
                        city = component['long_name']
                    elif 'postal_town' in types:
                        city = component['long_name']
                    elif 'administrative_area_level_2' in types:
                        city = component['long_name']
                    elif 'administrative_area_level_1' in types:
                        admin_level_1 = component['long_name']
                # 优先返回城市级结果,无结果则返回省/州级,都没有返回"Not Found"
                return city if city else admin_level_1 if admin_level_1 else "Not Found"
            return "No Results"
        return f"API Error: {result_data.get('status')}"
    return f"HTTP Error: {response.status_code}"

# 应用到数据集
data['City'] = data.apply(lambda row: get_city(row['Latitude'], row['Longitude'], api_key), axis=1)

关键修改说明:

  • 调整结果优先级:先遍历所有组件收集城市级别的值,最后再返回省/州级结果,避免提前返回更高层级区域
  • 完善状态检查:新增API返回status字段的判断,处理无结果、配额超限等场景,返回具体错误信息便于调试
  • 适配多地区类型:添加postal_town和administrative_area_level_2的判断,覆盖不同地区的地址组件规则
  • 明确返回逻辑:按城市→省/州→未找到的顺序返回,同时保留错误提示信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 12:59:59