经纬度是地理坐标系统,用于确定地球上任意点的位置。经度表示东西方向的位置,纬度表示南北方向的位置。通过经纬度反查城市名称是一种常见的地理编码(Geocoding)操作。
这是最常用的方法,通过调用第三方地理编码服务API实现。
import requests
def get_city_from_coords(lat, lon):
# 使用Nominatim API (OpenStreetMap)
url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}"
headers = {'User-Agent': 'YourAppName/1.0'}
try:
response = requests.get(url, headers=headers)
data = response.json()
return data.get('address', {}).get('city') or data.get('address', {}).get('town')
except Exception as e:
print(f"Error: {e}")
return None
# 示例使用
city = get_city_from_coords(40.7128, -74.0060) # 纽约坐标
print(city) # 输出: New York
from geopy.geocoders import Nominatim
from geopy.exc import GeocoderTimedOut
def get_city_local(lat, lon):
geolocator = Nominatim(user_agent="YourAppName")
try:
location = geolocator.reverse(f"{lat}, {lon}", exactly_one=True)
return location.raw['address'].get('city', '')
except GeocoderTimedOut:
return "Service timed out"
except Exception as e:
return f"Error: {str(e)}"
import reverse_geocoder as rg
def get_city_offline(lat, lon):
coordinates = (lat, lon)
results = rg.search(coordinates)
return results[0]['name']
# 示例使用
city = get_city_offline(48.8566, 2.3522) # 巴黎坐标
print(city) # 输出: Paris
原因:
解决方案:
原因:
解决方案:
解决方案:
以上方法可以根据具体需求选择最适合的方案,平衡准确性、成本和性能要求。
没有搜到相关的文章