geopy简单使用

文章目录

  • 安装 geopy 和 geopandas
    • 根据城市名或者经纬度相互转换
    • 测试两坐标之间的距离

安装 geopy 和 geopandas

  安装 geopygeopandas

pip install geopy

#安装 geopandas不能使用pip,会报错,在Anaconda下使用下conda
conda install -c conda-forge geopandas

根据城市名或者经纬度相互转换

import geopy
from geopy.geocoders import Nominatim
import geopandas

locator = Nominatim(user_agent = "myGeocoder")
location = locator.geocode("Champ de Mars, Paris, France")
print(location.address) 
# Champ de Mars, Place Edwige Feuillère, Quartier du Gros-Caillou, Paris, Île-de-France, France métropolitaine, 75007, France
from functools import partial
geolocator = Nominatim(user_agent = "myGeocoder")
geocode = partial(geolocator.geocode, language='en')
print(geocode('wuhan',language="en"))
reverse = partial(geolocator.reverse, language='en')
print(reverse("41.15166616,28.70958502"))
print(reverse("52.509669, 13.376294"))

#Wuhan, Jiang'an District, Wuhan, Hubei, 430062, China
#Hacımaşlı Mahallesi, Arnavutköy, Istanbul, Marmara Region, 34277, Turkey
#Potsdamer Platz, Bellevuestraße, Botschaftsviertel, Tiergarten, Mitte, Berlin, 10785, Germany

官方例子-链接
  根据地点获取经纬度

>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim(user_agent="specify_your_app_name_here")
>>> location = geolocator.geocode("175 5th Avenue NYC")
>>> print(location.address)
Flatiron Building, 175, 5th Avenue, Flatiron, New York, NYC, New York, ...
>>> print((location.latitude, location.longitude))
(40.7410861, -73.9896297241625)
>>> print(location.raw)
{'place_id': '9167009604', 'type': 'attraction', ...}

  根据经纬度获取地点

>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim(user_agent="specify_your_app_name_here")
>>> location = geolocator.reverse("52.509669, 13.376294")
>>> print(location.address)
Potsdamer Platz, Mitte, Berlin, 10117, Deutschland, European Union
>>> print((location.latitude, location.longitude))
(52.5094982, 13.3765983)
>>> print(location.raw)
{'place_id': '654513', 'osm_type': 'node', ...}

  这里可对输出的地点进行字符串切割,单独获取城市名或州名

location = geolocator.reverse("-37.68022156,144.84001")
print(location.address.split(",")[-3])
# Operations Road, Melbourne Airport, City of Hume, Victoria, 3045, Australia
# Victoria  切割后的字符串

测试两坐标之间的距离

>>> from geopy.distance import geodesic
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(geodesic(newport_ri, cleveland_oh).miles)
538.390445368

1. 参考链接

你可能感兴趣的:(Python,python)