def distance_matrix(origin, destination): """Return dictionary as trip_id: distance pairs.""" # Google Distance Matrix API set up base_url = ('https://maps.googleapis.com/maps/api/distancematrix/' 'json?') payload = { "origins": convert.location_list(origin), "destinations": convert.location_list(destination), "units": "imperial" } r = requests.get(base_url, params=payload) distance_meters = None distance_miles = None if r.status_code != 200: print('HTTP status code {} received, program terminated.'.format( r.status_code)) else: response_dict = json.loads(r.text) distance_meters = ( response_dict['rows'][0]['elements'][0]['distance']['value']) distance_miles = ( response_dict['rows'][0]['elements'][0]['distance']['text']) return (distance_meters, distance_miles)
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 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): params = { "origins": convert.location_list(origins), "destinations": convert.location_list(destinations) }
def dist_matrix_json(self,origins,destinations,**kwargs): client = self.gmaps from googlemaps import convert paras = {"origins": convert.location_list(origins), "destinations": convert.location_list(destinations), 'mode':"driving", 'units':"imperial" } for i in paras.keys(): if kwargs.get(i): paras[i] = kwargs.get(i) return client._request("/maps/api/distancematrix/json", paras)
def test_location_list(self): expected = "1,2|1,2" ll = [{"lat": 1, "lng": 2}, {"lat": 1, "lng": 2}] self.assertEqual(expected, convert.location_list(ll)) ll = [[1, 2], [1, 2]] self.assertEqual(expected, convert.location_list(ll)) ll = [(1, 2), [1, 2]] self.assertEqual(expected, convert.location_list(ll)) self.assertEqual(expected, convert.location_list(expected)) with self.assertRaises(TypeError): convert.latlng(1)
def __init__(self, locations, size=None, color=None, label=None): """ :param locations: Specifies the locations of the markers on the map. :type locations: list :param size: Specifies the size of the marker. :type size: str :param color: Specifies a color of the marker. :type color: str :param label: Specifies a single uppercase alphanumeric character to be displaied on marker. :type label: str """ super(StaticMapMarker, self).__init__() if size: self.params.append("size:%s" % size) if color: self.params.append("color:%s" % color) if label: if len(label) != 1 or not label.isupper() or not label.isalnum(): raise ValueError("Invalid label") self.params.append("label:%s" % label) self.params.append(convert.location_list(locations))
def findPathFromRoad(path, interpolate=True): gmaps = googlemaps.Client(key='AIzaSyBiRlZF9HEyYGEFTcxOTWJ6LYk1gzZ-QnE') _ROADS_BASE_URL = "https://roads.googleapis.com" params = {"path": convert.location_list(path), "interpolate": interpolate} response_result = gmaps._request("/v1/snapToRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract) # Check if there is a warning error there status_result = response_result.get("warningMessage", []) if status_result: print(status_result) road_result = response_result.get("snappedPoints", []) # Polygon road_lats = [] road_lons = [] for r in road_result: road_lats.append(r['location']['latitude']) road_lons.append(r['location']['longitude']) return road_lats, road_lons
def snap_to_roads(client, path, interpolate=False): """Snaps a path to the most likely roads travelled. Takes up to 100 GPS points collected along a route, and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along. :param path: The path to be snapped. :type path: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param interpolate: Whether to interpolate a path to include all points forming the full road-geometry. When true, additional interpolated points will also be returned, resulting in a path that smoothly follows the geometry of the road, even around corners and through tunnels. Interpolated paths may contain more points than the original path. :type interpolate: bool :rtype: A list of snapped points. """ params = {"path": convert.location_list(path)} if interpolate: params["interpolate"] = "true" return client._request("/v1/snapToRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get("snappedPoints", [])
def snap_to_roads(client, path, interpolate=False): """Snaps a path to the most likely roads travelled. Takes up to 100 GPS points collected along a route, and returns a similar set of data with the points snapped to the most likely roads the vehicle was traveling along. :param path: The path to be snapped. :type path: a single location, or a list of locations, where a location is a string, dict, list, or tuple :param interpolate: Whether to interpolate a path to include all points forming the full road-geometry. When true, additional interpolated points will also be returned, resulting in a path that smoothly follows the geometry of the road, even around corners and through tunnels. Interpolated paths may contain more points than the original path. :type interpolate: bool :rtype: A list of snapped points. """ params = {"path": convert.location_list(path)} if interpolate: params["interpolate"] = "true" return client._get("/v1/snapToRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get("snappedPoints", [])
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 nearest_roads(client, points): #Find the closest road segments for each point params = {"points": convert.location_list(points)} return client._request("/v1/nearestRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get("snappedPoints", [])
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): normal = lambda x: x restrictions = { mode: ("mode", ("driving", "walking", "bicycling", "transit", None)), avoid: ("avoid", ("tolls", "highways", "ferries", None)), } for val, (name, valid) in restrictions.items(): if val not in valid: raise ValueError("{} is not valid.".format(name)) variables = { "mode": (normal, mode), "language": (normal, language), "avoid": (normal, avoid), "units": (normal, units), "departure_time": (convert.time, departure_time), "arrival_time": (convert.time, arrival_time), "transit_mode": (partial(convert.join_list, '|'), transit_mode), "transit_routing_preference": (normal, transit_routing_preference), "traffic_model": (normal, traffic_model), } params = { 'origins': convert.location_list(origins), 'destinations': convert.location_list(destinations) } for var, (func, val) in variables.items(): if val: params[var] = func(val) return client._get('/maps/api/distancematrix/json', params)
def snapped_speed_limits(client, path): params = {"path": convert.location_list(path)} return client._request("/v1/speedLimits", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract)
async def snapped_speed_limits(client, path): params = {'path': convert.location_list(path)} return await client._request( '/v1/speedLimits', params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract, )
def distance_matrix_filter(origin, destination, trips): """Return dictionary as trip_id: distance pairs.""" trips_by_id = {trip.trip_id: trip for trip in trips} # Google Distance Matrix API set up base_url = ('https://maps.googleapis.com/maps/api/distancematrix/' 'json?') payload = { "origins": convert.location_list(origin), "destinations": convert.location_list(destination), "units": "imperial" } r = requests.get(base_url, params=payload) drop_off_distances = {} if r.status_code != 200: print('HTTP status code {} received, program terminated.'.format( r.status_code)) else: response_dict = json.loads(r.text) for offset, trip in enumerate(trips): cell = response_dict['rows'][0]['elements'][offset] if cell['status'] == 'OK': # Dictionary: key=trip_id, val=distance in meters drop_off_distances[trip.trip_id] = cell['distance']['value'] # print('{} to {}: {}.' # .format(src, dst, cell['distance']['text'])) drop_off_distances = { key: value for key, value in drop_off_distances.items() if value <= 72421 } drop_offs_nearby = {} for trip_idx in drop_off_distances: trip = trips_by_id[trip_idx] drop_offs_nearby[trip_idx] = trip return drop_offs_nearby
def snap_to_roads(client, path, interpolate=False): params = {"path": convert.location_list(path)} if interpolate: params["interpolate"] = "true" return client._get("/v1/snapToRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract)["snappedPoints"]
def directions(self, client, origin, destination, waypoints): params = { "origin": convert.latlng(origin), "destination": convert.latlng(destination) } waypoints = convert.location_list(waypoints) optimize_waypoints = True if optimize_waypoints: waypoints = "optimize:true|" + waypoints params["waypoints"] = waypoints return client._get("/maps/api/directions/json", params)["routes"][0]["waypoint_order"]
def snap_to_roads(client, path, interpolate=False): #Snaps a path to the most likely roads travelled params = {"path": convert.location_list(path)} if interpolate: params["interpolate"] = "true" return client._request("/v1/snapToRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get("snappedPoints", [])
async def nearest_roads(client, points): params = {'points': convert.location_list(points)} result = await client._request( '/v1/nearestRoads', params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract, ) return result.get('snappedPoints', [])
def elevation(client, locations): """ Provides elevation data for locations provided on the surface of the earth, including depth locations on the ocean floor (which return negative values) :param locations: List of latitude/longitude values from which you wish to calculate elevation data. :type locations: a single location, or a list of locations, where a location is a string, dict, list, or tuple :rtype: list of elevation data responses """ params = {"locations": convert.location_list(locations)} return client._get("/maps/api/elevation/json", params)["results"]
async def snap_to_roads(client, path, interpolate=False): params = {'path': convert.location_list(path)} if interpolate: params['interpolate'] = 'true' result = await client._request( '/v1/snapToRoads', params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract, ) return result.get('snappedPoints', [])
def mapMatch(latitude, longitude): lat_lng_list = [] n_lat = [] n_lng = [] for i in range(len(latitude)): lat_lng_list.append(str(latitude[i])+','+str(longitude[i])) for j in range(0,len(lat_lng_list),20): locations = convert.location_list(lat_lng_list[j:j+20]) params = {"path": locations, 'interpolate': "true", 'key': "AIzaSyBVtDB16c0FTGw1-L8iBuEdaQ937nwNXyI"} response = requests.get("https://roads.googleapis.com/v1/snapToRoads", params=params) newGpsValues = json.loads(response.text) for k in range(len(newGpsValues['snappedPoints'])): n_lat.append(newGpsValues['snappedPoints'][k]['location']['latitude']) n_lng.append(newGpsValues['snappedPoints'][k]['location']['longitude']) return n_lat,n_lng
def snapped_speed_limits(client, path): """Returns the posted speed limit (in km/h) for given road segments. The provided points will first be snapped to the most likely roads the vehicle was traveling along. :param path: The path of points to be snapped. :type path: a single location, or a list of locations, where a location is a string, dict, list, or tuple :rtype: dict with a list of speed limits and a list of the snapped points. """ params = {"path": convert.location_list(path)} return client._request("/v1/speedLimits", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract)
def __init__(self, points, weight=None, color=None, fillcolor=None, geodesic=None): """ :param points: Specifies the point through which the path will be built. :type points: list :param weight: Specifies the thickness of the path in pixels. :type weight: int :param color: Specifies a color of the path. :type color: str :param fillcolor: Indicates both that the path marks off a polygonal area and specifies the fill color to use as an overlay within that area. :type fillcolor: str :param geodesic: Indicates that the requested path should be interpreted as a geodesic line that follows the curvature of the earth. :type geodesic: bool """ super(StaticMapPath, self).__init__() if weight: self.params.append("weight:%s" % weight) if color: self.params.append("color:%s" % color) if fillcolor: self.params.append("fillcolor:%s" % fillcolor) if geodesic: self.params.append("geodesic:%s" % geodesic) self.params.append(convert.location_list(points))
def snapped_speed_limits(client, path): """Returns the posted speed limit (in km/h) for given road segments. The provided points will first be snapped to the most likely roads the vehicle was traveling along. :param path: The path of points to be snapped. :type path: a single location, or a list of locations, where a location is a string, dict, list, or tuple :rtype: dict with a list of speed limits and a list of the snapped points. """ params = {"path": convert.location_list(path)} return client._get("/v1/speedLimits", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract)
def nearest_roads(client, points): """Find the closest road segments for each point Takes up to 100 independent coordinates, and returns the closest road segment for each point. The points passed do not need to be part of a continuous path. :param points: The points for which the nearest road segments are to be located. :type points: a single location, or a list of locations, where a location is a string, dict, list, or tuple :rtype: A list of snapped points. """ params = {"points": convert.location_list(points)} return client._request("/v1/nearestRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get( "snappedPoints", [])
def nearest_roads(client, points): """Find the closest road segments for each point Takes up to 100 independent coordinates, and returns the closest road segment for each point. The points passed do not need to be part of a continuous path. :param points: The points for which the nearest road segments are to be located. :type points: a single location, or a list of locations, where a location is a string, dict, list, or tuple :rtype: A list of snapped points. """ params = {"points": convert.location_list(points)} return client._request("/v1/nearestRoads", params, base_url=_ROADS_BASE_URL, accepts_clientid=False, extract_body=_roads_extract).get("snappedPoints", [])
def elevation_along_path(client, path, samples): """ Provides elevation data sampled along a path on the surface of the earth. :param path: An encoded polyline string, or a list of latitude/longitude values from which you wish to calculate elevation data. :type path: string, dict, list, or tuple :param samples: The number of sample points along a path for which to return elevation data. :type samples: int :rtype: list of elevation data responses """ if type(path) is str: path = "enc:%s" % path else: path = convert.location_list(path) params = {"path": path, "samples": samples} return client._get("/maps/api/elevation/json", params)["results"]
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)
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', [])
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 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 static_map(client, size, center=None, zoom=None, scale=None, format=None, maptype=None, language=None, region=None, markers=None, path=None, visible=None, style=None): """ Downloads a map image from the Maps Static API. See https://developers.google.com/maps/documentation/maps-static/intro for more info, including more detail for each parameter below. :param size: Defines the rectangular dimensions of the map image. :type param: int or list :param center: Defines the center of the map, equidistant from all edges of the map. :type center: dict or list or string :param zoom: Defines the zoom level of the map, which determines the magnification level of the map. :type zoom: int :param scale: Affects the number of pixels that are returned. :type scale: int :param format: Defines the format of the resulting image. :type format: string :param maptype: defines the type of map to construct. There are several possible maptype values, including roadmap, satellite, hybrid, and terrain. :type maptype: string :param language: defines the language to use for display of labels on map tiles. :type language: string :param region: defines the appropriate borders to display, based on geo-political sensitivities. :type region: string :param markers: define one or more markers to attach to the image at specified locations. :type markers: StaticMapMarker :param path: defines a single path of two or more connected points to overlay on the image at specified locations. :type path: StaticMapPath :param visible: specifies one or more locations that should remain visible on the map, though no markers or other indicators will be displayed. :type visible: list of dict :param style: defines a custom style to alter the presentation of a specific feature (roads, parks, and other features) of the map. :type style: list of dict :rtype: iterator containing the raw image data, which typically can be used to save an image file locally. For example: ``` f = open(local_filename, 'wb') for chunk in client.static_map(size=(400, 400), center=(52.520103, 13.404871), zoom=15): if chunk: f.write(chunk) f.close() ``` """ params = {"size": convert.size(size)} if not markers: if not (center or zoom is not None): raise ValueError("both center and zoom are required" "when markers is not specifed") if center: params["center"] = convert.latlng(center) if zoom is not None: params["zoom"] = zoom if scale is not None: params["scale"] = scale if format: if format not in MAPS_IMAGE_FORMATS: raise ValueError("Invalid image format") params['format'] = format if maptype: if maptype not in MAPS_MAP_TYPES: raise ValueError("Invalid maptype") params["maptype"] = maptype if language: params["language"] = language if region: params["region"] = region if markers: params["markers"] = markers if path: params["path"] = path if visible: params["visible"] = convert.location_list(visible) if style: params["style"] = convert.components(style) response = client._request( "/maps/api/staticmap", params, extract_body=lambda response: response, requests_kwargs={"stream": True}, ) return response.iter_content()
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"))
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", [])