如何通过Python从经纬度坐标直接获取国家次区域信息?
直接通过经纬度获取国家次区域(subregion)的实现方案
如果你不想先通过经纬度转国名再查subregion,可以用以下两种方案直接实现需求:
方案1:结合逆地理编码与countryinfo库
利用逆地理编码工具直接获取国家ISO代码,再通过countryinfo查询次区域,全程无需手动处理国名:
from countryinfo import CountryInfo from geopy.geocoders import Nominatim def get_subregion(lat, lon): # 初始化Nominatim逆地理编码实例(自定义user_agent) geolocator = Nominatim(user_agent="your_app_name") # 反向解析坐标 location = geolocator.reverse(f"{lat}, {lon}", exactly_one=True) if not location: return None # 提取国家ISO 3166-1 alpha-2代码 country_code = location.raw.get('address', {}).get('country_code') if not country_code: return None # 通过国家代码查询subregion country = CountryInfo(country_code.upper()) return country.info().get('subregion') # 测试:南非约翰内斯堡坐标 print(get_subregion(-26.2041, 28.0473)) # 输出:Southern Africa
方案2:用reverse_geocoder+pycountry离线/轻量查询
reverse_geocoder是本地离线库,无需调用外部API,配合pycountry可直接获取标准次区域:
import reverse_geocoder as rg import pycountry def get_subregion_offline(lat, lon): # 本地查询坐标所属国家 results = rg.search((lat, lon)) if not results: return None country_code = results[0]['cc'] try: # 通过国家代码获取subregion country = pycountry.countries.get(alpha_2=country_code) return country.subregion except (KeyError, AttributeError): return None # 测试 print(get_subregion_offline(-26.2041, 28.0473)) # 输出:Southern Africa
注意事项
- 使用Nominatim时,需自定义
user_agent标识你的应用,避免被限制请求; reverse_geocoder是离线库,数据更新可能滞后,如果需要最新边界数据,建议定期更新库或使用在线服务;- 两种方案返回的
subregion分类均遵循ISO标准,和countryinfo的输出保持一致。
内容的提问来源于stack exchange,提问作者Yasir
相关产品推荐
相关产品推荐

