LoginSignup
6
6

More than 3 years have passed since last update.

【Python】Google Maps Platformを使ってGoogleマップの画像を作る

Posted at

Google Maps Platform の勉強。

APIキーを手に入れる

以下の2つのAPIを使う。

  • Maps Static API(マップに含まれている)
  • Geocoding API(プレイスに含まれている) gmp.png 画像取り忘れたけど1, 2, 3の順に進めればAPIキーが表示される。
    再度確認したい場合は「GCPコンソール > APIとサービス > 認証情報」

使うライブラリ

ドキュメントのページにリンク貼られてたのを使う。
Python client library for Google Maps API Web Services
$ pip install -U googlemaps

コード

Geocoding APIで経度と緯度取ってきてMaps Static API用のURL作るだけ。
いくつかのパラメータを設定できるようにした。

main.py
import googlemaps
import requests

MY_API_KEY = "あなたのAPI KEY"
URL_FORMAT = "https://maps.googleapis.com/maps/api/staticmap?center={}"\
    "&zoom={}&size={}&format={}{}&maptype=roadmap"\
    "&key={}"


def dl_image(filename, img_format, url):
    file_name = "{}.{}".format(filename, img_format[:3])
    res = requests.get(url)
    if res.status_code == 200:
        with open(file_name, "wb") as f:
            f.write(res.content)
    else:
        print("失敗")


def make_url(lat, lng, zoom, size, img_format, custom_icon):
    location = "{},{}".format(lat, lng)
    size_param = "{}x{}".format(*size)
    if custom_icon is None:
        icon_param = ""
    else:
        icon_param = "&markers=icon:{}|{}".format(custom_icon, location)
    url = URL_FORMAT.format(
        location, zoom, size_param, img_format, icon_param, MY_API_KEY)
    return url


def get_map_image(
        place, zoom, size=(600, 300), img_format="png",
        custom_icon=None, filename=None):
    """
    place : 場所\n
    zoom  : 1)世界 5)大陸 10)市 15)通り 20)建物\n
    size  : (width, height) 最大 640x640\n
    img_format : png(png8), png32, gif, jpg, jpg-baseline\n
    custom_icon : IconのURL
    """
    gmaps = googlemaps.Client(key=MY_API_KEY)
    geocode_result = gmaps.geocode(place)
    # for k, v in geocode_result[0].items():
    #     print("key : " + k)
    #     print(v)
    #     print("-" * 10)

    lat = geocode_result[0]["geometry"]["location"]["lat"]
    lng = geocode_result[0]["geometry"]["location"]["lng"]
    url = make_url(lat, lng, zoom, size, img_format, custom_icon)
    if filename is None:
        filename = place
    dl_image(filename, img_format, url)


if __name__ == "__main__":
    get_map_image("スカイツリー", 15)
    get_map_image(
        "スカイツリー", 15, custom_icon="https://i.imgur.com/zzmQALF.png",
        filename="スカイツリー_アイコン付き")

パラメータ

もっと色々出来る。公式ドキュメント参照。
https://developers.google.com/maps/documentation/maps-static/dev-guide

できた画像

カスタムアイコン無し

スカイツリー.png

カスタムアイコン有り

スカイツリーの位置にスカイツリーアイコン
スカイツリー_アイコン付き.png

わざわざ画像作りたくない

imgタグのsrcにurl指定すればok

sample.html
<html>
    <body>
        <img src="url" alt="地図">
    </body>
</html>

おわりに

他にもいっぱいAPIがあるんで使ってみたい。

おわり。

6
6
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
6
6