def get_walking_time(travel_from, travel_to, travel_mode): gmaps = googlemaps.Client(GMAPS_API_KEY) directions = directions_client.directions(origin=travel_from, destination=travel_to, client=gmaps, mode=travel_mode) return math.ceil(directions[0]["legs"][0]["distance"]["value"] / 60)
def get_Duration(start, finish): # gets duration of trip from JSON response data = directions.directions(rawGmapdata, start, finish) # slicing through JSON response for specific data duration_txt = data[0]['legs'][0]['duration']['text'] duration_val = data[0]['legs'][0]['duration']['value'] # building a list of related distance value [string, integer] duration = [duration_txt, duration_val] return duration
def get_Distances(start, finish): # gets distances from JSON return data = directions.directions(rawGmapdata, start, finish) # slicing through JSON response for specific data distance_string = data[0]['legs'][0]['distance']['text'] dist_meters = data[0]['legs'][0]['distance']['value'] # building a list of related distance value [string, integer] distances = [distance_string, dist_meters] return distances
def get_polyline_from_path(path): gclient = googlemaps.Client(key=settings.GOOGLE_MAPS_API_KEY) polyline = directions(gclient, path[0].get_location_tuple, path[-1].get_location_tuple, waypoints=[p.get_location_tuple for p in path[1:-2] ])[0]['overview_polyline']['points'] return decode_polyline(polyline)
def get_Addresses(start, finish): # gets addresses from JSON response data = directions.directions(rawGmapdata, start, finish) # slicing through JSON response for specific data start_address = data[0]['legs'][0]['start_address'] end_address = data[0]['legs'][0]['end_address'] # building a list of related distance value [string, string] addresses = [start_address, end_address] return addresses
def check_commute_time(self, request: CommuteRequest) -> int: directions_dict = directions( self.client, origin=request.from_address, destination=request.to_address, mode=self.config.mode, units='metric', language='en', region=self.config.region, **self._get_times(), )
def get_Coordinates(start, finish): # gets coordinates from JSON return data = directions.directions(rawGmapdata, start, finish) # slicing through JSON response for specific data start_coordinates = str( data[0]['legs'][0]['start_location']['lat']) + "%2C%20" + str( data[0]['legs'][0]['start_location']['lng']) end_coordinates = str( data[0]['legs'][0]['end_location']['lat']) + "%2C%20" + str( data[0]['legs'][0]['end_location']['lng']) # building a list of related distance value [string, string] coordinates = [start_coordinates, end_coordinates] return coordinates
def getDirections(origin,destination): gmaps = googlemaps.Client(key='AIzaSyC6ATRDCMZm2hv7Ay2nl3EgA98r2ebKHEQ') directionsResult = getDirectionsUsingGoogleMap.directions(gmaps,origin,destination) res = "" if len(directionsResult) == 0: return res for index,currStep in enumerate(directionsResult[0]["legs"][0]["steps"]): html = currStep["html_instructions"] soup = BeautifulSoup(html) text_parts = soup.findAll(text=True) text = ''.join(text_parts) res += str(index+1) +". "+ text +" travelMode: " +currStep["travel_mode"].lower()+", distance: " + currStep["distance"]["text"] +", duration: " +currStep["duration"]["text"]+ ".\n " return res
def _get_fastest_route(self): lyfter_start_coord = (self.lyfter_service_obj.source_lat, self.lyfter_service_obj.source_long) lyfter_dest_coord = (self.lyfter_service_obj.destination_lat, self.lyfter_service_obj.destination_long) routes = directions(self.gmaps, lyfter_start_coord, lyfter_dest_coord, alternatives=True, mode="driving") route_duration = [ route["legs"][0]["duration"]["value"] for route in routes ] fastest_route_index = route_duration.index(min(route_duration)) return routes[fastest_route_index]["legs"][0]["steps"]
def getDirections(origin, destination): gmaps = googlemaps.Client(key='AIzaSyC6ATRDCMZm2hv7Ay2nl3EgA98r2ebKHEQ') directionsResult = getDirectionsUsingGoogleMap.directions( gmaps, origin, destination) res = "" if len(directionsResult) == 0: return res for index, currStep in enumerate(directionsResult[0]["legs"][0]["steps"]): html = currStep["html_instructions"] soup = BeautifulSoup(html) text_parts = soup.findAll(text=True) text = ''.join(text_parts) res += str(index + 1) + ". " + text + " travelMode: " + currStep[ "travel_mode"].lower() + ", distance: " + currStep["distance"][ "text"] + ", duration: " + currStep["duration"]["text"] + ".\n " return res
def travel_time(rental, mode, work): origin = rental['address'] + ' ' + rental['postal_code'] arrival_time = datetime.strptime('Dec 9 2018 10:00AM', '%b %d %Y %I:%M%p') try: routes = directions.directions(gmaps, origin, work, mode, arrival_time=arrival_time) return round(routes[0]['legs'][0]['duration']['value'] / 60) except (KeyError, IndexError): return None except Exception as e: print(e) return None
def makeDirection(self, dirfrom, dirto): if self.gmaps is None: return "ERROR: you have to set API key" directions_result = directions.directions( self.gmaps, dirfrom, dirto, mode=self.mode, language=self.language, departure_time=self.departure) r = directions_result[0]['legs'] arr = r[0]['steps'] final_res = [] for obj in arr: arr_result = [] self.parseResult(obj, arr_result) final_res += arr_result arr_result = None return final_res
def get_directions(self): """ Makes a request to the python maps api, then transforms the result for the javascript maps api """ print('Getting directions for params:') print(self._params) self.directions = { 'routes': directions(self._client, self._params['origin'], self._params['destination'], mode=self._params['travelmode'], waypoints=self._params['waypoints']), 'travelmode': self._params['travelmode'].upper() } self._transform_for_renderer()
def route_generator(user_location, destination, client): pointA = user_location pointB = destination cli = client wp = waypoint_generator(pointA, pointB, cli) gmap_routes = [] route = directions.directions(cli, pointA, pointB, mode='walking', alternatives=True) print(len(route)) for i in range(len(route)): gmap_routes.append(route[i]) for waypoint in wp: route = directions.directions(cli, pointA, pointB, mode='walking', waypoints=waypoint) gmap_routes.append(route) gmap_routes.append( directions.directions(cli, pointA, pointB, mode='walking', waypoints=[wp[0], wp[2]])) gmap_routes.append( directions.directions(cli, pointA, pointB, mode='walking', waypoints=[wp[0], wp[3]])) gmap_routes.append( directions.directions(cli, pointA, pointB, mode='walking', waypoints=[wp[1], wp[2]])) gmap_routes.append( directions.directions(cli, pointA, pointB, mode='walking', waypoints=[wp[1], wp[3]])) return gmap_routes
for line in f: if line.startswith(('#', '\n')): continue return line client = Client(key=GetGoogleKey( os.path.join(cwd,'google-key.txt') ) ) loc = geocoder(client) latlong = loc.coords("Triantafyllopoy 35 thessaloniki") wp = directions.directions(client, origin="Γεωργίου Γεννηματά καλαμαριά", destination="Triantafyllopouloy 35 Pylaia", mode='driving', language="el", units="metric") wr = shapefile.Writer(shapefile.POLYLINE) wr.autoBalance = 1 wr.field("Route") w_critical_points = shapefile.Writer(shapefile.POINT) w_critical_points.autoBalance = 1 w_critical_points.field("Directions", "C", 254) for route in wp: points = decode(route['overview_polyline']['points']) wr.poly(shapeType=3, parts=[points]) wr.record(route['summary'].encode("cp1253")) for leg in route['legs']:
def GetGoogleKey(file=None): with open(file, "r") as f: for line in f: if line.startswith(('#', '\n')): continue return line client = Client(key=GetGoogleKey(os.path.join(cwd, 'google-key.txt'))) loc = geocoder(client) latlong = loc.coords("Triantafyllopoy 35 thessaloniki") wp = directions.directions(client, origin="Γεωργίου Γεννηματά καλαμαριά", destination="Triantafyllopouloy 35 Pylaia", mode='driving', language="el", units="metric") wr = shapefile.Writer(shapefile.POLYLINE) wr.autoBalance = 1 wr.field("Route") w_critical_points = shapefile.Writer(shapefile.POINT) w_critical_points.autoBalance = 1 w_critical_points.field("Directions", "C", 254) for route in wp: points = decode(route['overview_polyline']['points']) wr.poly(shapeType=3, parts=[points]) wr.record(route['summary'].encode("cp1253"))
def clusterize() -> dict: def valid_point(d): if not 'latitude' in d.keys() or not 'longitude' in d.keys(): return False return True def point_eq(p1, p2): return p1['latitude'] == p2['latitude'] and p1['longitude'] == p2['longitude'] def cluster_eq(c1, c2): return c1['coords']['lat'] == c2['coords']['lat'] and c2['coords']['lon'] == c1['coords']['lon'] def find_cluster(p, clist): for c in clist: for pp in c['points']: if point_eq(p, pp): return c raise Exception('Something went very wrong') data = request.json or request.get_json() if not data: raise ValidationError(errors=dict(objects='empty request')) points = data.get('objects', []) if len(points) < 1: raise ValidationError(errors=dict(objects='cannot clusterize 0 points')) for p in points: if not valid_point(p): raise ValidationError( errors=dict(objects='all points must have at least latitude and longitude attributes')) clusters = get_clusters(points=points, max_dist=500) gmaps_client: Client = Client(key=GMAPS_KEY) origin_cluster = find_cluster(points[0], clusters) dest_cluster = find_cluster(points[-1], clusters) waypoint_clusters = [c for c in clusters if (not cluster_eq(c, origin_cluster)) and (not cluster_eq(c, dest_cluster))] waypoints = ["{},{}".format(c['coords']['lat'], c['coords']['lon']) for c in waypoint_clusters] # Request directions via public transit dirs = directions( client=gmaps_client, origin="{},{}".format(origin_cluster['coords']['lat'], origin_cluster['coords']['lon']), destination="{},{}".format(dest_cluster['coords']['lat'], dest_cluster['coords']['lon']), waypoints=waypoints, mode="walking", optimize_waypoints=True ) ordered = [origin_cluster] waypoint_clusters_points = [(c, Point(lat=c['coords']['lat'], lon=c['coords']['lon'])) for c in waypoint_clusters] for leg in dirs[0]['legs']: dest = leg['steps'][-1]['end_location'] dest = Point(lat=dest['lat'], lon=dest['lng'], payload=dest) if not waypoint_clusters_points: continue best_match = 0 best_diff = Point.distance(dest, waypoint_clusters_points[best_match][1]) for i, c in enumerate(waypoint_clusters_points): diff = Point.distance(dest, c[1]) if best_diff > diff: best_match = i best_diff = diff ordered.append(waypoint_clusters_points[best_match][0]) del waypoint_clusters_points[best_match] ordered.append(dest_cluster) return make_response(jsonify(dict(clusters=ordered)))
def Directions(self, origin, destination, waypoints): results = directions.directions(self.GoogleClient, origin, destination, waypoints=waypoints,\ mode="driving", optimize_waypoints=True) return results
def google_maps_directions(start, end, **kwargs): """Returns directions from Google Maps.""" return directions(api, start, end, **kwargs)