geopy是Python關于地理位置的一個第三方庫,用這個庫來進行位址位置資訊的查詢和轉換非常友善,本文介紹關于geopy的常用的幾種用法
geopy的安裝
pip install geopy
根據位址查詢坐标及詳細資訊
>>> import json, logging
>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim()
>>> location = geolocator.geocode("北京天安門")
>>> print location.address
天安門, 1, 西長安街, 崇文, 北京市, 東城區, 北京市, 100010, 中國
>>> print (location.latitude, location.longitude)
(39.90733345, 116.391244079988)
>>> print json.dumps(location.raw, indent=4, ensure_ascii=False, encoding='utf8')
{
"display_name": "天安門, 1, 西長安街, 崇文, 北京市, 東城區, 北京市, 100010, 中國",
"importance": 0.00025,
"place_id": "74005413",
"lon": "116.391244079988",
"lat": "39.90733345",
"osm_type": "way",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
"osm_id": "25097203",
"boundingbox": [
"39.9072273",
"39.9075343",
"116.3906566",
"116.3918428"
],
"type": "yes",
"class": "building"
}
根據坐标資訊查詢位址
>>> import json, logging
>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim()
>>> location = geolocator.reverse("39.90733345,116.391244079988")
>>> print location.address
天安門, 1, 西長安街, 崇文, 北京市, 東城區, 北京市, 100010, 中國
>>> print json.dumps(location.raw, indent=4, ensure_ascii=False, encoding='utf8')
{
"display_name": "天安門, 1, 西長安街, 崇文, 北京市, 東城區, 北京市, 100010, 中國",
"place_id": "74005413",
"lon": "116.391244079988",
"boundingbox": [
"39.9072273",
"39.9075343",
"116.3906566",
"116.3918428"
],
"osm_type": "way",
"licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
"osm_id": "25097203",
"lat": "39.90733345",
"address": {
"building": "天安門",
"city": "北京市",
"house_number": "1",
"country": "中國",
"suburb": "東城區",
"state": "北京市",
"postcode": "100010",
"country_code": "cn",
"road": "西長安街"
}
}