def distance_matrix(client, origins, destinations, mode=None, language=None, avoid=None, units=None, departure_time=None, arrival_time=None, transit_mode=None, transit_routing_preference=None, traffic_model=None, region=None): params = { "origins": convert.location_list(origins), "destinations": convert.location_list(destinations) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if language: params["language"] = language if avoid: if avoid not in ["tolls", "highways", "ferries"]: raise ValueError("Invalid route restriction.") params["avoid"] = avoid if units: params["units"] = units if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model if region: params["region"] = region #print(client._request("/maps/api/distancematrix/json", params)) return client._request("/maps/api/distancematrix/json", params)
def directions(client, origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=True, transit_mode=None, transit_routing_preference=None, traffic_model=None): params = { "origin": convert.latlng(origin), "destination": convert.latlng(destination) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if waypoints: waypoints = convert.location_list(waypoints) if optimize_waypoints: waypoints = "optimize:true|" + waypoints params["waypoints"] = waypoints if alternatives: params["alternatives"] = "true" if avoid: params["avoid"] = convert.join_list("|", avoid) if language: params["language"] = language if units: params["units"] = units if region: params["region"] = region if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model return client._get("/maps/api/directions/json", params)["routes"][0]['waypoint_order']
def timezone(client, location, timestamp=None, language=None): """Get time zone for a location on the earth, as well as that location's time offset from UTC. :param location: The latitude/longitude value representing the location to look up. :type location: string, dict, list, or tuple :param timestamp: Timestamp specifies the desired time as seconds since midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied. Times before 1970 can be expressed as negative values. Optional. Defaults to ``datetime.utcnow()``. :type timestamp: int or datetime.datetime :param language: The language in which to return results. :type language: string :rtype: dict """ params = { "location": convert.latlng(location), "timestamp": convert.time(timestamp or datetime.utcnow()) } if language: params["language"] = language return client._request("/maps/api/timezone/json", params)
def timezone(client, location, timestamp=None, language=None): """Get time zone for a location on the earth, as well as that location's time offset from UTC. :param location: The latitude/longitude value representing the location to look up. :type location: dict or tuple :param timestamp: Timestamp specifies the desired time as seconds since midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to determine whether or not Daylight Savings should be applied. Times before 1970 can be expressed as negative values. Optional. Defaults to ``datetime.now()``. :type timestamp: int or datetime.datetime :param language: The language in which to return results. :type language: string :rtype: dict """ location = convert.latlng(location) timestamp = convert.time(timestamp or datetime.now()) params = { "location": location, "timestamp": timestamp } if language: params["language"] = language return client._get( "/maps/api/timezone/json", params)
def timezone(location: str, timestamp=None, language=None): # taken directly from Google's API example on GitHub params = { "location": convert.latlng(getlatlong(location)), "timestamp": convert.time(timestamp or datetime.utcnow()) } if language: params["language"] = language ret = gmaps._request("/maps/api/timezone/json", params) return (ret["rawOffset"] + ret["dstOffset"]) / 3600
def get_bus_full_price(origin, destination, year, month, day, hour, minutes): try: endpoint = 'https://maps.googleapis.com/maps/api/directions/json?' api_key = '' dep_time = datetime.datetime(year, month, day, hour, minutes) dep_time = convert.time(dep_time) nav_request = 'origin={}&destination={}&key={}&departure_time={}&mode=transit&transit_mode=bus&language=zh-TW'.format(quote(origin), quote(destination), api_key, dep_time) request = endpoint + nav_request #print(request) response = urllib.request.urlopen(request).read() directions = json.loads(response.decode('utf-8')) #print(directions) ticket_fare = directions['routes'][0]['fare']['text'] except: ticket_fare = None return ticket_fare
def distance_matrix(client, origins, destinations, mode=None, language=None, avoid=None, units=None, departure_time=None, arrival_time=None, transit_mode=None, transit_routing_preference=None, traffic_model=None): """ Gets travel distance and time for a matrix of origins and destinations. :param origins: One or more locations and/or latitude/longitude values, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. :type origins: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param destinations: One or more addresses and/or lat/lng values, to which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. :type destinations: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param mode: Specifies the mode of transport to use when calculating directions. Valid values are "driving", "walking", "transit" or "bicycling". :type mode: string :param language: The language in which to return results. :type language: string :param avoid: Indicates that the calculated route(s) should avoid the indicated features. Valid values are "tolls", "highways" or "ferries". :type avoid: string :param units: Specifies the unit system to use when displaying results. Valid values are "metric" or "imperial". :type units: string :param departure_time: Specifies the desired time of departure. :type departure_time: int or datetime.datetime :param arrival_time: Specifies the desired time of arrival for transit directions. Note: you can't specify both departure_time and arrival_time. :type arrival_time: int or datetime.datetime :param transit_mode: Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are "bus", "subway", "train", "tram", "rail". "rail" is equivalent to ["train", "tram", "subway"]. :type transit_mode: string or list of strings :param transit_routing_preference: Specifies preferences for transit requests. Valid values are "less_walking" or "fewer_transfers". :type transit_routing_preference: string :param traffic_model: Specifies the predictive travel time model to use. Valid values are "best_guess" or "optimistic" or "pessimistic". The traffic_model parameter may only be specified for requests where the travel mode is driving, and where the request includes a departure_time. :rtype: matrix of distances. Results are returned in rows, each row containing one origin paired with each destination. """ params = { "origins": convert.location_list(origins), "destinations": convert.location_list(destinations) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if language: params["language"] = language if avoid: if avoid not in ["tolls", "highways", "ferries"]: raise ValueError("Invalid route restriction.") params["avoid"] = avoid if units: params["units"] = units if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model return client._request("/maps/api/distancematrix/json", params)
def distance_matrix(client, origins, destinations, mode=None, language=None, avoid=None, units=None, departure_time=None, arrival_time=None, transit_mode=None, transit_routing_preference=None, traffic_model=None): """ Gets travel distance and time for a matrix of origins and destinations. :param origins: One or more locations and/or latitude/longitude values, from which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. :type origins: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param destinations: One or more addresses and/or lat/lng values, to which to calculate distance and time. If you pass an address as a string, the service will geocode the string and convert it to a latitude/longitude coordinate to calculate directions. :type destinations: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param mode: Specifies the mode of transport to use when calculating directions. Valid values are "driving", "walking", "transit" or "bicycling". :type mode: string :param language: The language in which to return results. :type language: string :param avoid: Indicates that the calculated route(s) should avoid the indicated features. Valid values are "tolls", "highways" or "ferries". :type avoid: string :param units: Specifies the unit system to use when displaying results. Valid values are "metric" or "imperial". :type units: string :param departure_time: Specifies the desired time of departure. :type departure_time: int or datetime.datetime :param arrival_time: Specifies the desired time of arrival for transit directions. Note: you can't specify both departure_time and arrival_time. :type arrival_time: int or datetime.datetime :param transit_mode: Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are "bus", "subway", "train", "tram", "rail". "rail" is equivalent to ["train", "tram", "subway"]. :type transit_mode: string or list of strings :param transit_routing_preference: Specifies preferences for transit requests. Valid values are "less_walking" or "fewer_transfers". :type transit_routing_preference: string :param traffic_model: Specifies the predictive travel time model to use. Valid values are "best_guess" or "optimistic" or "pessimistic". The traffic_model parameter may only be specified for requests where the travel mode is driving, and where the request includes a departure_time. :rtype: matrix of distances. Results are returned in rows, each row containing one origin paired with each destination. """ params = { "origins": convert.location_list(origins), "destinations": convert.location_list(destinations) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if language: params["language"] = language if avoid: if avoid not in ["tolls", "highways", "ferries"]: raise ValueError("Invalid route restriction.") params["avoid"] = avoid if units: params["units"] = units if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model return client._get("/maps/api/distancematrix/json", params)
def directions(client, origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=False, transit_mode=None, transit_routing_preference=None, traffic_model=None): """Get directions between an origin point and a destination point. :param origin: The address or latitude/longitude value from which you wish to calculate directions. :type origin: string, dict, list, or tuple :param destination: The address or latitude/longitude value from which you wish to calculate directions. :type destination: string, dict, list, or tuple :param mode: Specifies the mode of transport to use when calculating directions. One of "driving", "walking", "bicycling" or "transit" :type mode: string :param waypoints: Specifies an array of waypoints. Waypoints alter a route by routing it through the specified location(s). :type waypoints: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param alternatives: If True, more than one route may be returned in the response. :type alternatives: bool :param avoid: Indicates that the calculated route(s) should avoid the indicated features. :type avoid: list or string :param language: The language in which to return results. :type language: string :param units: Specifies the unit system to use when displaying results. "metric" or "imperial" :type units: string :param region: The region code, specified as a ccTLD ("top-level domain" two-character value. :type region: string :param departure_time: Specifies the desired time of departure. :type departure_time: int or datetime.datetime :param arrival_time: Specifies the desired time of arrival for transit directions. Note: you can't specify both departure_time and arrival_time. :type arrival_time: int or datetime.datetime :param optimize_waypoints: Optimize the provided route by rearranging the waypoints in a more efficient order. :type optimize_waypoints: bool :param transit_mode: Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are "bus", "subway", "train", "tram", "rail". "rail" is equivalent to ["train", "tram", "subway"]. :type transit_mode: string or list of strings :param transit_routing_preference: Specifies preferences for transit requests. Valid values are "less_walking" or "fewer_transfers" :type transit_routing_preference: string :param traffic_model: Specifies the predictive travel time model to use. Valid values are "best_guess" or "optimistic" or "pessimistic". The traffic_model parameter may only be specified for requests where the travel mode is driving, and where the request includes a departure_time. :type units: string :rtype: list of routes """ params = { "origin": convert.latlng(origin), "destination": convert.latlng(destination) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if waypoints: waypoints = convert.location_list(waypoints) if optimize_waypoints: waypoints = "optimize:true|" + waypoints params["waypoints"] = waypoints if alternatives: params["alternatives"] = "true" if avoid: params["avoid"] = convert.join_list("|", avoid) if language: params["language"] = language if units: params["units"] = units if region: params["region"] = region if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model return client._get("/maps/api/directions/json", params)["routes"]
def get_transport_info(origin, destination, year, month, day, hour, minutes): endpoint = 'https://maps.googleapis.com/maps/api/directions/json?' api_key = '' dep_time = datetime.datetime(year, month, day, hour, minutes) dep_time = convert.time(dep_time) # 子url 限定大眾交通工具(除了航運)、中文輸入輸出、多條路線 nav_request = 'origin={}&destination={}&key={}&departure_time={}&mode=transit&avoid=ferries&language=zh-TW&alternatives=true'.format( quote(origin), quote(destination), api_key, dep_time) request = endpoint + nav_request response = urllib.request.urlopen(request).read() # 讀進google api吐出的內容 directions = json.loads(response.decode('utf-8')) # 用json整理資訊 routes_list = [] #print(len(directions['routes'][0]['legs'][0]['steps'])) for k in range(len(directions['routes'])): # 分出路線 for i in range(len(directions['routes'][k]['legs'])): # 分出個別交通方式 leg = directions['routes'][k]['legs'][i]['steps'] routes_list.append(leg) means_list = [] if directions['status'] == 'ZERO_RESULTS': print('I found no route.') # 結果顯示找不到路徑 else: for i in range(len(routes_list)): transport_means = [] # 單一路線的詳細資訊 for item in routes_list[i]: # 個別交通方式的資訊 if item['travel_mode'] == 'TRANSIT': if item['transit_details']['line']['vehicle'][ 'type'] == 'BUS': # 路線編號 起站 訖站 if len(item['transit_details']['line'] ['short_name']) == 4: transport_info = [] transport_info.append( item['transit_details']['line']['vehicle'] ['type']) # BUS transport_info.append( item['transit_details']['line'] ['short_name']) # 路線編號 transport_info.append( item['transit_details']['departure_stop'] ['name']) # 起站名 transport_info.append( item['transit_details']['arrival_stop'] ['name']) # 訖站名 departure_date_info = datetime.datetime.fromtimestamp( item['transit_details']['departure_time'] ['value']) # 從UTC格式(秒)轉成datetime格式 transport_info.append( departure_date_info.strftime('%Y/%m/%d') ) # 2019/12/05 //23:00(高鐵,日期,時間分兩個變數) transport_info.append( item['transit_details']['departure_time'] ['text']) #上午/下午00:00 arrival_date_info = datetime.datetime.fromtimestamp( item['transit_details']['arrival_time'] ['value']) # 從UTC格式(秒)轉成datetime格式 transport_info.append( arrival_date_info.strftime('%Y/%m/%d') ) # 2019/12/05 //23:00(高鐵,日期,時間分兩個變數) transport_info.append( item['transit_details']['arrival_time'] ['text']) # 上午/下午00:00 time = item['transit_details'][ 'departure_time']['text'].split(':') dep_hour = time[0][2:] dep_minute = time[1] fare = GoogleAPI.get_bus_full_price( item['transit_details']['departure_stop'] ['name'], item['transit_details']['arrival_stop'] ['name'], year=int(year), month=int(month), day=int(day), hour=int(dep_hour), minutes=int(dep_minute)) transport_info.append(fare) # 全票票價(用來抓半票票價) transport_means.append(transport_info) elif item['transit_details']['line']['vehicle'][ 'type'] == 'HEAVY_RAIL': # 高鐵/台鐵 if item['transit_details']['line'][ 'short_name'] == '高鐵': # 高鐵 日期 格式是2019/12/13 起站 訖站 車次號碼 transport_info = [] transport_info.append( item['transit_details']['line']['vehicle'] ['type']) # HEAVY_RAIL transport_info.append( item['transit_details']['line'] ['short_name']) # 高鐵 transport_info.append( item['transit_details'] ['trip_short_name']) # 編號 transport_info.append( item['transit_details']['departure_stop'] ['name']) # 起站名 transport_info.append( item['transit_details']['arrival_stop'] ['name']) # 訖站名 date_info = datetime.datetime.fromtimestamp( item['transit_details']['departure_time'] ['value']) # 從UTC格式(秒)轉成datetime格式 transport_info.append( date_info.strftime('%Y/%m/%d') ) # 2019/12/05 //23:00(高鐵,日期,時間分兩個變數) transport_info.append( item['transit_details']['departure_time'] ['text']) # 上午/下午00:00 date_info = datetime.datetime.fromtimestamp( item['transit_details']['arrival_time'] ['value']) # 從UTC格式(秒)轉成datetime格式 transport_info.append( date_info.strftime('%Y/%m/%d') ) # 2019/12/05 //23:00(高鐵,日期,時間分兩個變數) transport_info.append( item['transit_details']['arrival_time'] ['text']) # 上午/下午00:00 transport_means.append(transport_info) else: # 台鐵 車次 起站 訖站 時間 transport_info = [] transport_info.append( item['transit_details']['line']['vehicle'] ['type']) # HEAVY_RAIL transport_info.append( item['transit_details']['line'] ['short_name']) # 車種 transport_info.append( item['transit_details'] ['trip_short_name']) # 車次 transport_info.append( item['transit_details']['departure_stop'] ['name']) # 起站名 transport_info.append( item['transit_details']['arrival_stop'] ['name']) # 訖站名 date_info = datetime.datetime.fromtimestamp( item['transit_details']['departure_time'] ['value']) # 從UTC格式(秒)轉成datetime格式 transport_info.append( date_info.strftime('%Y/%m/%d') ) # 2019/12/05 //23:00(高鐵,日期,時間分兩個變數) transport_info.append( item['transit_details']['departure_time'] ['text']) # 上午/下午00:00 date_info = datetime.datetime.fromtimestamp( item['transit_details']['departure_time'] ['value']) # 從UTC格式(秒)轉成datetime格式 transport_info.append( date_info.strftime('%Y/%m/%d') ) # 2019/12/05 //23:00(高鐵,日期,時間分兩個變數 transport_info.append( item['transit_details']['arrival_time'] ['text']) # 上午/下午00:00 transport_means.append(transport_info) means_list.append(transport_means) return means_list # 各路線中交通方式的詳細資訊
def directions(origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=False, transit_mode=None, transit_routing_preference=None, traffic_model=None): # also directly from GitHub params = { "origin": convert.latlng(getlatlong(origin)), "destination": convert.latlng(getlatlong(destination)) } if mode: if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if waypoints: waypoints = convert.location_list(waypoints) if optimize_waypoints: waypoints = "optimize:true|" + waypoints params["waypoints"] = waypoints if alternatives: params["alternatives"] = "true" if avoid: params["avoid"] = convert.join_list("|", avoid) if language: params["language"] = language if units: params["units"] = units if region: params["region"] = region if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model return gmaps._request("/maps/api/directions/json", params).get("routes", [])[0]["legs"][0]
def directions(client, origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=False, transit_mode=None, transit_routing_preference=None, traffic_model=None): """Get directions between an origin point and a destination point. :param origin: The address or latitude/longitude value from which you wish to calculate directions. :type origin: string, dict, list, or tuple :param destination: The address or latitude/longitude value from which you wish to calculate directions. :type destination: string, dict, list, or tuple :param mode: Specifies the mode of transport to use when calculating directions. One of "driving", "walking", "bicycling" or "transit" :type mode: string :param waypoints: Specifies an array of waypoints. Waypoints alter a route by routing it through the specified location(s). :type waypoints: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param alternatives: If True, more than one route may be returned in the response. :type alternatives: bool :param avoid: Indicates that the calculated route(s) should avoid the indicated features. :type avoid: list or string :param language: The language in which to return results. :type language: string :param units: Specifies the unit system to use when displaying results. "metric" or "imperial" :type units: string :param region: The region code, specified as a ccTLD ("top-level domain" two-character value. :type region: string :param departure_time: Specifies the desired time of departure. :type departure_time: int or datetime.datetime :param arrival_time: Specifies the desired time of arrival for transit directions. Note: you can't specify both departure_time and arrival_time. :type arrival_time: int or datetime.datetime :param optimize_waypoints: Optimize the provided route by rearranging the waypoints in a more efficient order. :type optimize_waypoints: bool :param transit_mode: Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are "bus", "subway", "train", "tram", "rail". "rail" is equivalent to ["train", "tram", "subway"]. :type transit_mode: string or list of strings :param transit_routing_preference: Specifies preferences for transit requests. Valid values are "less_walking" or "fewer_transfers" :type transit_routing_preference: string :param traffic_model: Specifies the predictive travel time model to use. Valid values are "best_guess" or "optimistic" or "pessimistic". The traffic_model parameter may only be specified for requests where the travel mode is driving, and where the request includes a departure_time. :type units: string :rtype: list of routes """ params = { "origin": convert.latlng(origin), "destination": convert.latlng(destination) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if waypoints: waypoints = convert.location_list(waypoints) if optimize_waypoints: waypoints = "optimize:true|" + waypoints params["waypoints"] = waypoints if alternatives: params["alternatives"] = "true" if avoid: params["avoid"] = convert.join_list("|", avoid) if language: params["language"] = language if units: params["units"] = units if region: params["region"] = region if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model return client._request("/maps/api/directions/json", params).get("routes", [])
def test_time(self): self.assertEqual("1409810596", convert.time(1409810596)) dt = datetime.datetime.fromtimestamp(1409810596) self.assertEqual("1409810596", convert.time(dt))
def distance_between(origins, destinations, mode="driving", language=None, avoid=None, units=None, departure_time=None, arrival_time=None, transit_mode=None, transit_routing_preference=None, traffic_model=None, region=None): params = { "origins": convert.location_list(origins), "destinations": convert.location_list(destinations) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if language: params["language"] = language if avoid: if avoid not in ["tolls", "highways", "ferries"]: raise ValueError("Invalid route restriction.") params["avoid"] = avoid if units: params["units"] = units if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: params["traffic_model"] = traffic_model if region: params["region"] = region client = googlemaps.Client(key='AIzaSyBWiIuZnjTM3pZcpr6e8xnCnupC2nKwJ_4') response = client._request("/maps/api/distancematrix/json", params) if (response.get("status") != 'OK'): print(response) return response else: rows = response.get("rows") elements = rows[0].get("elements") text_distance = elements[0].get("distance").get("text") duration_text = elements[0].get("duration").get("text") valuableData = f"The distance between {origins} and {destinations} is {text_distance} and it will take you about {duration_text} to reach {destinations} by {mode}" print(valuableData) return valuableData #print(distance_between( "96 symonds street auckland 1010", "mt albert primary auckland"))
async def directions(client, origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=False, transit_routing_preference=None, transit_mode=None, traffic_model=None): params = { 'origin': convert.latlng(origin), 'destination': convert.latlng(destination) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ['driving', 'walking', 'bicycling', 'transit']: raise ValueError('Invalid travel mode.') params['mode'] = mode if waypoints: waypoints = convert.location_list(waypoints) if optimize_waypoints: waypoints = 'optimize:true|' + waypoints params['waypoints'] = waypoints if alternatives: params['alternatives'] = 'true' if avoid: params['avoid'] = convert.join_list('|', avoid) if language: params['language'] = language if units: params['units'] = units if region: params['region'] = region if departure_time: params['departure_time'] = convert.time(departure_time) if arrival_time: params['arrival_time'] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError('Should not specify both departure_time and' 'arrival_time.') if transit_mode: params['transit_mode'] = convert.join_list('|', transit_mode) if transit_routing_preference: params['transit_routing_preference'] = transit_routing_preference if traffic_model: params['traffic_model'] = traffic_model result = await client._request('/maps/api/directions/json', params) return result.get('routes', [])
params["alternatives"] = "true" if avoid: params["avoid"] = convert.join_list("|", avoid) if language: params["language"] = language if units: params["units"] = units if region: params["region"] = region if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference if traffic_model: