[python] google map api 로 거리 및 시간 추출

Seongkeun·2023년 1월 24일
1

Python

목록 보기
5/8
post-thumbnail

개요

google map api 로 두 지점간의 거리와 걸린 시간을 추출하고자한다. 정확히는 google map api 중 'directions' 를 사용하였다. google maps api key여기 로 받으러 가면 된다. google maps APIdirections API, distance matrix API, roads API, routes API 등 여러가지가 있는데 하나의 키로 통용 하고 있다.

google map api 사용법

import packages

import json
import pandas as pd
import requests

initial setting

# google map api
google_map_api_key="YOUR_API_KEY"
how_to_go="driving" #options : walking, driving, bicycling, transit => transit : public transportation

# gps coordinates
origin = "13.76515,100.53904"
destination = "13.7329,100.52898"

initialize api url

url="https://maps.googleapis.com/maps/api/directions/json?"\
f"&origin={origin}"\
f"&destination={destination}"\
f"&mode={how_to_go}"\
f"&key={google_map_api_key}"
url

- output

'https://maps.googleapis.com/maps/api/directions/json?&origin=13.76515,100.53904&destination=13.7329,100.52898&mode=driving&key=YOUR_API_KEY'

parsing the json

response = requests.get(url)
response = response.json()
response

- output

{'geocoded_waypoints': [{'geocoder_status': 'OK',
   'place_id': 'ChIJuWPz8bCe4jAR5dvTSk4O8uk',
   'types': ['establishment', 'point_of_interest', 'transit_station']},
  {'geocoder_status': 'OK',
   'place_id': 'ChIJo7J0OdWY4jARefHzpv1802M',
   'types': ['bakery',
    'establishment',
    'food',
    'point_of_interest',
    'store']}],
 'routes': [{'bounds': {'northeast': {'lat': 13.7713441, 'lng': 100.5424492},
    'southwest': {'lat': 13.7328599, 'lng': 100.5192035}},
   'copyrights': 'Map data ©2023 Google',
   'legs': [{'distance': {'text': '7.9 km', 'value': 7895},
     'duration': {'text': '15 mins', 'value': 890},
     'end_address': '989 Phaya Thai Rd, Khwaeng Pathum Wan, Khet Pathum Wan, Krung Thep Maha Nakhon 10330, Thailand',
     'end_location': {'lat': 13.7328599, 'lng': 100.5289614},
     'start_address': 'Victory Monument(Ko Phahonyothin), Khwaeng Thanon Phaya Thai, Khet Ratchathewi, Krung Thep Maha Nakhon 10400, Thailand',
     'start_location': {'lat': 13.7650899, 'lng': 100.5389112},
     'steps': [{'distance': {'text': '0.4 km', 'value': 405},
       'duration': {'text': '1 min', 'value': 64},
       'end_location': {'lat': 13.7633385, 'lng': 100.5420374},
       'html_instructions': 'Head <b>southeast</b> on <b>ถ. ราชวิถี</b> 
       
       ...
       
       ,
   'summary': 'ทางพิเศษศรีรัช',
   'warnings': [],
   'waypoint_order': []}],
 'status': 'OK'}

위 json 결과 값에서 내가 필요한 부분은 가장 하단의 status 부분과 중간 routeslegs 부분이다. legs 안 쪽을 살펴보면 내가 필요한 distance : 거리duration : 걸린 시간 이 있는 것을 확인할 수 있다. postman 이나 chrome 의 json viewer 로 보면 깔끔하게 파악 할 수 있다.

to DataFrame

json 데이터를 DataFrame 으로 바꿔주는 함수가 pandas 에 내장되어 있다. 함수는 pd.json_normalize() 이다. 위 json 데이터에서 필요한 부분을 DataFrame 으로 바꿔보자

data=pd.json_normalize(
    data=response,
    record_path=['routes',['legs']],
    meta=['status']
)
data

- output

필요한 칼럼 재정리

DataFrame 이 너무 지저분해보인다. 필요한 칼럼만 따로 추출하자

data.loc[:,['distance.text','distance.value','duration.text','duration.value']]

- output

response 로 직접 접근

response(json data) 로 직접 접근해서 위와 같이 만들 수도 있다. duration.value 하나만 필요하거나 할 때 위 방법보다 더 요긴하게 사용할 수 있다 ( 메모리 부분 절약 )

df=pd.DataFrame(columns=['distance_text','distance_value','duration_text','duration_value'])

if response['status'] == 'OK':
    distance_text = response['routes'][0]['legs'][0]['distance']['text']
    distance_value = response['routes'][0]['legs'][0]['distance']['value']
    duration_text = response['routes'][0]['legs'][0]['duration']['text']
    duration_value = response['routes'][0]['legs'][0]['duration']['value']
    df=df.append({'distance_text':distance_text, 'distance_value':distance_value, 'duration_text':duration_text,'duration_value':duration_value}, ignore_index=True)
    
df

- output

profile
지혜는 지식에서 비롯된다

0개의 댓글