본문 바로가기

사업/python 으로 모든걸 할수있다

구글 대중교통 경로 api 이용하기 google transit direction api

반응형

 

 

developers.google.com/maps/documentation/directions/overview

 

Overview  |  Directions API  |  Google Developers

Calculate directions between locations using the Google Maps Directions API. Find an introduction to using the API and references on the available parameters.

developers.google.com

들어간다

한달에 무료 크래딧 200불씩 주는데 카드 등록 해야함.

여기 써있는대로 시키는대로 하시고..

 

 

키 발급까진 쉬운데 라이브러리에 들어가서 사용하고자하는 구체적인 API 명을 검색해서 "사용"을 눌러주어야 함.

 

import urllib.request, json
def transit_route(origin,destination,d_time):
    #Google MapsDdirections API endpoint
    endpoint = "https://maps.googleapis.com/maps/api/directions/json?"
    api_key= "api_key"
    nav_request = 'origin={}&destination={}&departure_time={}&mode=transit&transit_routing_preference=fewer_transfers&key={}'.format(origin,destination,d_time,api_key)
    request = endpoint + nav_request
    #Sends the request and reads the response.
    response = urllib.request.urlopen(request).read()
    #Loads response as JSON
    directions = json.loads(response)
    return directions

저기 위에 "api_key"에 본인이 발급받은 키 넣으면 끝!

 

api 형식은 JSON 형식으로 주는데 그냥 들여쓰기? 에 맞추어 ['인덱스']으로 원하는 값을 찾아나가면 된다.

내가 파싱에 쓴 코드도 공유

def parsing(directions):
    '''
    Inputs: the api result
    Outputs: total travel time and location of nearby station
    '''
    if directions['status'] == 'OK':
        # unit is seconds
        total_tt = directions['routes'][0]['legs'][0]['duration']['value']
        steps = directions['routes'][0]['legs'][0]['steps']
        mode_list = [i['travel_mode'] for i in steps]
        tt_list = [i['duration']['value'] for i in steps]
        if 'TRANSIT' in mode_list:
            s = mode_list.index('TRANSIT')
            station_loc = steps[s]['transit_details']['departure_stop']['location']
        else:
            station_loc = None
        return total_tt, station_loc, mode_list, tt_list
    else: # if api call is not valid, return None
        return None, None, None, None

 

데이터 셋 구축을 위한 크롤링은 제제를 받을 수 있으니 주의하자

 

 

 

toughbear.tistory.com/entry/python-args와-kwargs-의미와-사용

 

[python] *args와 **kwargs 의미와 사용

python으로 개발하다가 외부라이브러리를 쓰다보면 많이 보는 글자가 바로 *args 또는 **kwargs 다. 한마디로 말해서 어떤 값을 넣을진 모르는데 *args는 값을 넣으면 함수에 변수가 튜플형태로 입력되

toughbear.tistory.com

API 코드짤때 활용하면 좋을듯

반응형