LoginSignup
3
5

More than 5 years have passed since last update.

緯度経度から都市の名前を得る

Last updated at Posted at 2018-04-13

Google Maps Geocoding API の リバースジオコーディング の例です。

reverse_geo.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#   reverse_geo.py
#
#                       Apr/30/2019
#
# ------------------------------------------------------------------
import  os
import  sys
import  json
import  requests
from dotenv import load_dotenv
#
# ------------------------------------------------------------------
def parser_results(json_str):
    dict_aa = json.loads(json_str)
#
    city = ""
    pref = ""
    components = dict_aa['results'][0]['address_components']
    for it in range(len(components)):
        unit_aa = components[it]
        if (unit_aa['types'][0] == "locality"):
            city = unit_aa['short_name']
        elif (unit_aa['types'][0] == "administrative_area_level_1"):
            pref = unit_aa['short_name']
#
    return city,pref
# ------------------------------------------------------------------
def get_city_pref_proc(api_key,lat,lon):
    url_aa="https://maps.googleapis.com/maps/api/geocode/json?latlng="
    url=url_aa + str(lat) + "," + str(lon) + "&language=ja&key=" + api_key
    res = requests.get(url)
    json_str=res.text
    city,pref = parser_results(json_str)
    print(lat,lon,city,pref)
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
dotenv_path = '.env'
load_dotenv(dotenv_path)
api_key = os.environ.get("API_KEY")
#
get_city_pref_proc(api_key,43.08,141.35)
get_city_pref_proc(api_key,36.56,139.88)
get_city_pref_proc(api_key,35.91,139.66)
get_city_pref_proc(api_key,35.68,139.76)
get_city_pref_proc(api_key,35.16,136.90)
get_city_pref_proc(api_key,34.70,135.50)
get_city_pref_proc(api_key,33.59,130.42)
get_city_pref_proc(api_key,31.56,130.56)
get_city_pref_proc(api_key,26.21,127.68)
#
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

API_KEY は置き換えて下さい。

.env
API_KEY="***************************************"

実行結果

$ ./reverse_geo.py 
*** 開始 ***
43.08 141.35 札幌市 北海道
36.56 139.88 宇都宮市 栃木県
35.91 139.66 さいたま市 埼玉県
35.68 139.76 千代田区 東京都
35.16 136.9 名古屋市 愛知県
34.7 135.5 大阪市 大阪府
33.59 130.42 福岡市 福岡県
31.56 130.56 鹿児島市 鹿児島県
26.21 127.68 那覇市 沖縄県
*** 終了 ***
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5