LoginSignup
0
0

More than 1 year has passed since last update.

google map APIのトラフィックを削減するために。 To save google map API traffics.

Last updated at Posted at 2022-08-20

初めに
First

google mapのAPIは使いすぎると料金が発生してしまう。そのために余計な通信を節約して最小限に圧縮できるようにしたい。
If too use gooogle map API, the fee occuer. So, I wanna save extra traffics and minimize.

概要
outline

場所のjsonファイルを作る時と航空写真を取得するときに、すでに調べてデータがある場所のデータを取らないように判定を加える。
Add jedge which except process researched locations, when create location's json file and get aerial photograph.

My code

import pandas as pd
import urllib.error
import urllib.request
import json,os
from pygeocoder import Geocoder
import googlemaps

googleapikey='key'
pixel = '640x480'
scale='18'

location = ["国会議事堂","沼津","香港","Seattle","Schloss Neuschwanstein"
            ,"big ben","Mont Saint-Michel","東京都庁","Rio de Janeiro","北京"]

loc_dict = []

def loc_csv():
    df=pd.DataFrame(data=loc_dict)
    #delete duplications
    df=df.drop_duplicates('loc')
    fn="./loc_csv/loc_info.csv"
    if os.path.exists(fn) is True:
        with open(fn,'a',encoding='utf-8-sig') as f:
            df.to_csv(fn)
    else:
        #export csv
        df.to_csv(fn)

def dl_image():
    loc = pd.read_csv("./loc_csv/loc_info.csv",index_col="Unnamed: 0")
    #convert to list
    lats = loc['lat'].values.tolist()
    lngs = loc['lng'].values.tolist()
    locs = loc['loc'].values.tolist()
    
    #html setting
    html = ["https://maps.googleapis.com/maps/api/staticmap?center=",
     "&maptype=hybrid",
     "&size=",
     "&sensor=false",
     "&zoom=",
     "&markers=",
     "&key="]

    for lt,lg,lc in zip(lats,lngs,locs):

        axis = str(lt) + "," + str(lg)
        #URL setting
        url = html[0] + axis + html[1] + html[2] + pixel + html[3] + html[4] + scale + html[5] + axis + html[6] + googleapikey
        #photo path
        dst_path =  './loc_photo/' + str(lc) + ".png"
        #if the photo already exist,no use google map api.
        if os.path.exists(dst_path) is True:
            pass
        else:
            try:
                data = urllib.request.urlopen(url).read()
            #url error
            except urllib.error.URLError as e:
                print(e)
            else:
                with open(dst_path,mode="wb") as f:
                    f.write(data)

def mk_dir():
    if os.path.isdir("./loc_csv") == True:
        pass
    else:
        os.system("mkdir loc_csv")
    if os.path.isdir("./loc_info") == True:
        pass
    else:
        os.system("mkdir loc_info")
    if os.path.isdir("./loc_photo") == True:
        pass
    else:
        os.system("mkdir loc_photo")



def main():
    gmaps = googlemaps.Client(key=googleapikey)
    for i in location:
        address =u"" + i
        fname='loc_info/'+ address + '.json'
        #if the json file already exist, no use google map api.
        if os.path.exists(fname) == True:
            pass
        else:
            try:
                result = gmaps.geocode(address)
            except Exception as e:
                print(e)
            else:  
                lat=result[0]["geometry"]["location"]["lat"]
                lng=result[0]["geometry"]["location"]["lng"]
                format_ad=result[0]["formatted_address"]
                loc_dict.append({'loc':i,'lat':lat,'lng':lng,'formatted_address':format_ad})
                with open(fname,'w',encoding='utf-8-sig') as f:
                    print(json.dumps(result,indent=2,ensure_ascii=False),file=f)
    #Are elements zero or not?
    if len(loc_dict) == 0:
        pass
    else:
        #make directories
        mk_dir()
        #make a csv file
        loc_csv()
        #download location photos
        dl_image()


if __name__ == "__main__":
    main()

取得した航空写真
Geted aerial photographes

国会議事堂.png
Mont Saint-Michel.png

参考サイト
Refered sites

作り方
how to creating map program

resolve encoding error with binary mode

https://bobbyhadz.com/blog/python-valueerror-binary-mode-doesnt-take-an-encoding-argument#:~:text=The%20Python%20%22ValueError%3A%20binary%20mode,remove%20the%20encoding%20keyword%20argument.

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