1. 程式人生 > >Python地理位置資訊庫geopy的使用(一):基本使用

Python地理位置資訊庫geopy的使用(一):基本使用

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": "西長安街"
    }
}