def get_coordinates_from_encoded_polyline(directions): if 'overview_polyline' in directions[0].keys(): lat_long_set = convert.decode_polyline( directions[0]['overview_polyline']['points']) return lat_long_set else: return False
def test_polyline_decode(self): syd_mel_route = ("rvumEis{y[`NsfA~tAbF`bEj^h{@{KlfA~eA~`AbmEghAt~D|e@j" "lRpO~yH_\\v}LjbBh~FdvCxu@`nCplDbcBf_B|wBhIfhCnqEb~D~" "jCn_EngApdEtoBbfClf@t_CzcCpoEr_Gz_DxmAphDjjBxqCviEf}" "B|pEvsEzbE~qGfpExjBlqCx}BvmLb`FbrQdpEvkAbjDllD|uDldD" "j`Ef|AzcEx_Gtm@vuI~xArwD`dArlFnhEzmHjtC~eDluAfkC|eAd" "hGpJh}N_mArrDlr@h|HzjDbsAvy@~~EdTxpJje@jlEltBboDjJdv" "KyZpzExrAxpHfg@pmJg[tgJuqBnlIarAh}DbN`hCeOf_IbxA~uFt" "|A|xEt_ArmBcN|sB|h@b_DjOzbJ{RlxCcfAp~AahAbqG~Gr}AerA" "`dCwlCbaFo]twKt{@bsG|}A~fDlvBvz@tw@rpD_r@rqB{PvbHek@" "vsHlh@ptNtm@fkD[~xFeEbyKnjDdyDbbBtuA|~Br|Gx_AfxCt}Cj" "nHv`Ew\\lnBdrBfqBraD|{BldBxpG|]jqC`mArcBv]rdAxgBzdEb" "{InaBzyC}AzaEaIvrCzcAzsCtfD~qGoPfeEh]h`BxiB`e@`kBxfA" "v^pyA`}BhkCdoCtrC~bCxhCbgEplKrk@tiAteBwAxbCwuAnnCc]b" "{FjrDdjGhhGzfCrlDruBzSrnGhvDhcFzw@n{@zxAf}Fd{IzaDnbD" "joAjqJjfDlbIlzAraBxrB}K~`GpuD~`BjmDhkBp{@r_AxCrnAjrC" "x`AzrBj{B|r@~qBbdAjtDnvCtNzpHxeApyC|GlfM`fHtMvqLjuEt" "lDvoFbnCt|@xmAvqBkGreFm~@hlHw|AltC}NtkGvhBfaJ|~@riAx" "uC~gErwCttCzjAdmGuF`iFv`AxsJftD|nDr_QtbMz_DheAf~Buy@" "rlC`i@d_CljC`gBr|H|nAf_Fh{G|mE~kAhgKviEpaQnu@zwAlrA`" "G~gFnvItz@j{Cng@j{D{]`tEftCdcIsPz{DddE~}PlnE|dJnzG`e" "G`mF|aJdqDvoAwWjzHv`H`wOtjGzeXhhBlxErfCf{BtsCjpEjtD|" "}Aja@xnAbdDt|ErMrdFh{CzgAnlCnr@`wEM~mE`bA`uD|MlwKxmB" "vuFlhB|sN`_@fvBp`CxhCt_@loDsS|eDlmChgFlqCbjCxk@vbGxm" "CjbMba@rpBaoClcCk_DhgEzYdzBl\\vsA_JfGztAbShkGtEhlDzh" "C~w@hnB{e@yF}`D`_Ayx@~vGqn@l}CafC") points = convert.decode_polyline(syd_mel_route) self.assertAlmostEqual(-33.86746, points[0]["lat"]) self.assertAlmostEqual(151.207090, points[0]["lng"]) self.assertAlmostEqual(-37.814130, points[-1]["lat"]) self.assertAlmostEqual(144.963180, points[-1]["lng"])
def test_polyline_round_trip(self): test_polyline = ("gcneIpgxzRcDnBoBlEHzKjBbHlG`@`IkDxIi" "KhKoMaLwTwHeIqHuAyGXeB~Ew@fFjAtIzExF") points = convert.decode_polyline(test_polyline) actual_polyline = convert.encode_polyline(points) self.assertEqual(test_polyline, actual_polyline)
def get_points_along_path(maps_api_key, _from, _to, departure_time=None, period=5): """ Generates a series of points along the route, such that it would take approx `period` seconds to travel between consecutive points This function is primarily meant to simulate a car along a route. The output of this function is equivalent to the geo coordinates of the car every 5 seconds (assuming period = 5) _from = human friendly from address that google maps can understand _to = human friendly to address that google maps can understand departure_time - primarily used to identify traffic model, defaults to current time period = how frequently should co-ordinates be tracked? Defaults to 5 seconds The output is an OrderedDict. Key is the time in seconds since trip start, value is a tuple representing (lat, long) in float """ if not departure_time: departure_time = datetime.now() gmaps = googlemaps.Client(key=maps_api_key) directions = gmaps.directions(_from, _to, departure_time=departure_time) steps = directions[0]['legs'][0]['steps'] all_lats = [] all_lngs = [] all_times = [] step_start_duration = 0 step_end_duration = 0 for step in steps: step_end_duration += step['duration']['value'] points = decode_polyline(step['polyline']['points']) distances = [] lats = [] lngs = [] start = None for point in points: if not start: start = point distance = 0 else: distance = _calculate_distance(start, point) distances.append(distance) lats.append(point['lat']) lngs.append(point['lng']) missing_times = numpy.interp(distances[1:-1], [distances[0], distances[-1]], [step_start_duration, step_end_duration]).tolist() times = [step_start_duration] + missing_times + [step_end_duration] times = [_round_up_time(t, period) for t in times] times, lats, lngs = _fill_missing_times(times, lats, lngs, period) all_lats += lats all_lngs += lngs all_times += times step_start_duration = step_end_duration points = OrderedDict() for p in zip(all_times, all_lats, all_lngs): points[p[0]] = (round(p[1], 5), round(p[2], 5)) return points
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_points_along_path(maps_api_key, _from, _to, departure_time=None, period=600): if not departure_time: departure_time = datetime.now() gmaps = googlemaps.Client(key=maps_api_key) directions = gmaps.directions(_from, _to, departure_time=departure_time) #print(directions) steps = directions[0]['legs'][0]['steps'] all_lats = [] all_lngs = [] all_times = [] step_start_duration = 0 step_end_duration = 0 for step in steps: step_end_duration += step['duration']['value'] points = decode_polyline(step['polyline']['points']) distances = [] lats = [] lngs = [] start = None for point in points: if not start: start = point distance = 0 else: distance = _calculate_distance(start, point) distances.append(distance) lats.append(point['lat']) lngs.append(point['lng']) missing_times = numpy.interp(distances[1:-1], [distances[0], distances[-1]], [step_start_duration, step_end_duration]).tolist() times = [step_start_duration] + missing_times + [step_end_duration] times = [_round_up_time(t, period) for t in times] times, lats, lngs = _fill_missing_times(times, lats, lngs, period) all_lats += lats all_lngs += lngs all_times += times step_start_duration = step_end_duration points = OrderedDict() for p in zip(all_times, all_lats,all_lngs): points[p[0]] = (round(p[1], 5), round(p[2],5)) return points
def convert_to_point_routes(map_routes): point_routes = [] for route in map_routes: lats = [] lngs = [] if type(route) is dict: # alternative route, indexes differently than waypoint route polyline = route['overview_polyline']['points'] else: # waypoint route, indexes differently than alternative route polyline = route[0]['overview_polyline']['points'] route_points = convert.decode_polyline(polyline) for i in range(len(route_points) - 1): if i == 0: prev = (route_points[i]['lat'], route_points[i]['lng']) proceed = True if i > 0: pointA = (route_points[i]['lat'], route_points[i]['lng']) euclidean_distance = ((pointA[0] - prev[0])**2 + (pointA[1] - prev[1])**2)**0.5 if euclidean_distance > 0.0002: proceed = True prev = pointA else: proceed = False if proceed: pointA = (route_points[i]['lat'], route_points[i]['lng']) lats.append(pointA[0]) lngs.append(pointA[1]) pointB = (route_points[i + 1]['lat'], route_points[i + 1]['lng']) # print(pointB) # pointB = (legs[i+1][0]['lat'], legs[i+1][0]['lng']) # print(pointB) euclidean_distance = ((pointA[0] - pointB[0])**2 + (pointA[1] - pointB[1])**2)**0.5 num = int(euclidean_distance // 0.0004) - 1 if num > 0: interm, _, _ = points(pointA, pointB, num) for x in interm: lats.append(x[0]) lngs.append(x[1]) lats.append(pointB[0]) lngs.append(pointB[1]) point_routes.append({'latitudes': lats, 'longitudes': lngs}) return point_routes
def next_coordinate(list_of_polyline_strings): for _poly_string in list_of_polyline_strings: coordinate_obj_list = con.decode_polyline(_poly_string) for coord in coordinate_obj_list: yield coord
# For each step, get the encoded polyline. Level does not matter since Street View API will be called. # Each point on the polyline will need to be decoded into a latitude/longitude pair. # For each step, Google provides a written description (HTML) of the directions. Parse the directions into human-friendly text instructions. directions_polylines = [] instructions = [] for j in range(0, len(directions_steps)): # Pull polyline for each step directions_polylines.append(directions_steps[j]['polyline']['points']) # Pull and parse HTML directions instructions.append( parse_html(str(directions_steps[j]['html_instructions']))) # Decode polyline into tuple list of lat/lng coordindates decode_coordinates = [] for polyline in directions_polylines: decode_coordinates.append(convert.decode_polyline(polyline)) # Calculate the bearing(i.e. heading, point of view) for every coordinate pair; # GET request from Google Maps Street View API for each coordinate pair and the corresponding bearing. # Calculating the bearing will ensure that we retrieve the correct image for the direction the user would be facing when following the directions. bearing_list = [] request_url = 'https://maps.googleapis.com/maps/api/streetview?size=600x300&location=' request_delim = ',' request_heading = '&heading=' request_url_metadata = 'https://maps.googleapis.com/maps/api/streetview/metadata?size=600x300&location=' # Fix the pitch (tilt of the viewer) so ensure that images are captured as if looking straight ahead. request_pitch_api_key = '&pitch=-0.76&key=' + api_key page_seq = 1 # Keeping tracking of sequence will allow the images to be identified and placed in the correct order. img_list = []