def simple(): # import datetime # import StringIO #get the polyline map using api: get_activity_map() from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure # from matplotlib.dates import DateFormatter import polyline m = session['map'] summary_lat_lon = polyline.decode(m.summary_polyline) fig=Figure() ax=fig.add_subplot(111) lats = [i[0] for i in summary_lat_lon] lons = [i[1] for i in summary_lat_lon] # x=[] # y=[] # now=datetime.datetime.now() # delta=datetime.timedelta(days=1) # for i in range(10): # x.append(now) # now+=delta # y.append(random.randint(0, 1000)) # ax.plot_date(x, y, '-') # ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) ax.scatter(lons,lats) fig.autofmt_xdate() canvas=FigureCanvas(fig) png_output = StringIO.StringIO() canvas.print_png(png_output) response=make_response(png_output.getvalue()) response.headers['Content-Type'] = 'image/png' return response
def iter_points(route, max_dist=0): """A generator that yields each (lat, lon) pair along the given route. If max_dist is non-zero, additional points will be linearly-interpolated between any two points in the route that are farther than max_dist apart. """ prev_point = None for leg in route['legs']: for step in leg['steps']: points = step['polyline']['points'] for point in polyline.decode(points): if prev_point and max_dist > 0: # Do we need to interpolate between the previous point and # the current one? dist = distance_between(point, prev_point) if dist > max_dist: steps = math.ceil(dist / max_dist) # Unpack coordinates from our point tuples and do # simple linear interpolation of the lat and long # coordinates individually. next_lat, next_lon = point prev_lat, prev_lon = prev_point lat_dist = next_lat - prev_lat lon_dist = next_lon - prev_lon for i in xrange(int(steps)): cur_lat = prev_lat + (1/steps * lat_dist) cur_lon = prev_lon + (1/steps * lon_dist) yield (cur_lat, cur_lon) prev_lat, prev_lon = cur_lat, cur_lon yield point prev_point = point
def test_decode_official_example(self): d = polyline.decode('_p~iF~ps|U_ulLnnqC_mqNvxq`@') self.assertEqual(d, [ (38.500, -120.200), (40.700, -120.950), (43.252, -126.453) ])
def directions_with_scores(request): if request.method == 'POST': params = request.POST elif request.method == 'GET': params = request.GET else: return HttpResponseNotFound('<h1>Page not found</h1>') # check parameters if 'origin' not in params.keys() or 'destination' not in params.keys(): return HttpResponseBadRequest('<h1>Bad Request</h1>origin and destination parameters required') # get directions directions_result = gmapsRequest.directions(params['origin'], params['destination']) points = directions_result[0]['overview_polyline']['points'] # calculate the safety_score line = polyline.decode(points) [crime, xinfo, yinfo] = loadRasterData() safety_score = reweight_linelist(line, crime, xinfo, yinfo) # form JSON response response = {'directions': directions_result, 'safety_score': safety_score} return JsonResponse(response)
def test_decode_official_example_precision(self): d = polyline.decode('_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI', 6) self.assertEqual(d, [ (38.500, -120.200), (40.700, -120.950), (43.252, -126.453) ])
def set_points(polyline): """Given a polyline as a ROS message, normalize and store the points.""" if polyline is not None: points = pl.decode(polyline.data) # Calculate the y and x ranges (in kilometers). # This is because we must later flip the polyline points # (this is because a polyline point is a tuple of (lat, lon) while we # want (x, y) image coordinates), which # makes the y and x range calculations invalid later on. y_range, x_range = interpolate.dimensions(points) # Store y and x ranges. g['y_range'] = y_range g['x_range'] = x_range # Flip the points because we want the top of the image # to represent north. g['points'] = [(y, -x) for (x, y) in points] # Calculate top left and bottom right coordinates # after flipping the polyline points. top_left, bottom_right = interpolate.corners(g['points']) g['top_left'] = top_left g['bottom_right'] = bottom_right g['ll_height'] = abs(top_left[1] - bottom_right[1]) g['ll_width'] = abs(top_left[0] - bottom_right[0]) # Based on the accurate y and x ranges, calculate a height and width # that will scale our final image to our specified pixels_per_m # (pixels per meter) parameter. # Note that this is distinct from `image_height` and `image_width`, # which are the height and width of the current window that will be # passed to the frame merger! g['height'] = int(round(g['y_range'] * Y_SCALE)) g['width'] = int(round(g['x_range'] * X_SCALE)) # Store the normalized points. g['points'] = interpolate.normalized_points(g['points'], g['top_left'], g['ll_height'], g['ll_width'], IMINFO)
def main(): access_token = getToken() if access_token == None: return redirectAuth() client = Client(access_token=access_token) athlete = client.get_athlete() # Get current athlete details #if you want a simple output of first name, last name, just use this line: #return athlete.firstname + ' ' + athlete.lastname #now get most recent activity for this athlete... names = [] maps = [] for a in client.get_activities(before = "2016-08-12T00:00:00Z", limit=1): names.append(a.name) maps.append(a.map) # another simple output for this bit is to return the name of the route #return names[0] # but a sightly more complicated output is this matplotlib figure -- m = maps[0] summary_lat_lon = polyline.decode(m.summary_polyline) lats = [i[0] for i in summary_lat_lon] lons = [i[1] for i in summary_lat_lon] session['name']=names[0] session['lats']=lats session['lons']=lons return redirect('/simple.png')
def query(line): toprint = [] name, x1, y1, x2, y2 = line[:-1].split(',') output = json.loads(urllib2.urlopen(base_otp+'fromPlace='+y1+'%2C'+x1+'&toPlace='+y2+'%2C'+x2).read()) if output['plan'] is not None: for itin in output['plan']['itineraries']: for leg in itin['legs']: toprint.append(""" <Placemark> <name>%s</name> <description>%s</description> <styleUrl>#GreenLine</styleUrl> <LineString> <coordinates>""" % (escape(name), leg['legGeometry']['length'])) toprint.append(' '.join([','.join([str(p[0]), str(p[1])]) for p in polyline.decode(leg['legGeometry']['points'])])) toprint.append(""" </coordinates> </LineString> </Placemark>""") hit.add(x1+','+y1) hit.add(x2+','+y2) else: if (x2+','+y2 not in hit and x2+','+y2 not in nothit) or (x1+','+y1 not in hit and x1+','+y1 not in nothit): toprint.append(""" <Placemark> <name>%s</name> <description>%s</description> <styleUrl>#redLine</styleUrl>""" % (escape(name), "No result")) if True: if (x2+','+y2 not in hit and x2+','+y2 not in nothit): toprint.append(""" <Point> <coordinates> %s,%s </coordinates> </Point>""" % (x2, y2)) nothit.add(x2+','+y2) else: toprint.append(""" <Point> <coordinates> %s,%s </coordinates> </Point>""" % (x1, y1)) nothit.add(x1+','+y1) else: toprint.append(""" <LineString> <coordinates>""") toprint.append(' '.join([','.join([str(p[0]), str(p[1])]) for p in [(x1, y1), (x2, y2)]])) toprint.append(""" </coordinates> </LineString>""") toprint.append(""" </Placemark>""") return '\n'.join(toprint)
def group_by_segments(rides): segments = defaultdict(list) for ride in rides: points = polyline.decode(ride.route.path) for i in range(0, len(points)-1): src = points[i] dst = points[i+1] segments[_sorted_tuple((src, dst))].append(ride) logger.info("Got {} distinct segments".format(len(segments))) return [(polyline.encode([src, dst]), rides) for (src, dst), rides in segments.items()]
def break_polyline(directions): """ Function: break_polyline ---------------------------- takes an overview polyline of a navigation path and breaks it up into smaller intervals directions: gmaps.directions object with origin and destination returns: a list of latitude and longitude points at the polyline intervals """ latlon = [] length = len(polyline.decode(directions[0]['overview_polyline']['points'])) path = polyline.decode(directions[0]['overview_polyline']['points']) #print length #print float(directions[0]['legs'][0]['distance']['text'][:3]) for i in range(0, length, 20): #finds every 20th polyline coordinate latlon.append((path[i][0],path[i][1])) return latlon
def make_route_map(data): threshold = session['threshold'] ts = [0.5, 1, 2, 5, 10, 20, 90] zs = [10, 10, 10, 5, 5, 1] #zoom 1 is all the way out zooms = dict(zip(ts, zs)) #zooms dictionary to get a proper zoom for a given threshold gmap = gmplot.GoogleMapPlotter(session['lat_med'], session['lon_med'], zooms[threshold]) for m in data.maps.values: summary_lat_lon = polyline.decode(m.summary_polyline) lats = [i[0] for i in summary_lat_lon] lons = [i[1] for i in summary_lat_lon] gmap.plot(lats,lons,'blue', size=100, alpha=0.5, edge_width=5) output = StringIO() gmap.draw_file(output, session['gid']) return output.getvalue()
def test_decode_multiple_points_precision(self): d = polyline.decode('o}oolA~ieoO???~{Bo}@??o}@?????_|B????n}@??n}@', 6) self.assertEqual(d, [ (40.641, -8.654), (40.641, -8.654), (40.641, -8.656), (40.642, -8.656), (40.642, -8.655), (40.642, -8.655), (40.642, -8.655), (40.642, -8.653), (40.642, -8.653), (40.642, -8.653), (40.641, -8.653), (40.641, -8.654) ])
def test_decode_multiple_points(self): d = polyline.decode('gu`wFnfys@???nKgE??gE?????oK????fE??fE') self.assertEqual(d, [ (40.641, -8.654), (40.641, -8.654), (40.641, -8.656), (40.642, -8.656), (40.642, -8.655), (40.642, -8.655), (40.642, -8.655), (40.642, -8.653), (40.642, -8.653), (40.642, -8.653), (40.641, -8.653), (40.641, -8.654) ])
def make_file(route): if (os.path.exists('output') == False): os.mkdir('output') steps = route['legs'][0]['steps'] points = [] for step in steps: points_in_step = polyline.decode(step['polyline']['points']) for point in points_in_step: dist_to_point = step['distance']['value'] / len(points_in_step) points.append(point + tuple([dist_to_point])) tree = get_xml_tree(points) tree.write('output/out.gpx', xml_declaration=True, encoding='utf-8') print('Created out.gpx') print('From: ' + args[0] + ', To: ' + args[1])
def _label_waypoints(city_from, city_to, path): points = polyline.decode(path) def _label_step(src_country, dst_country, points): if len(points) == 0: return [] if len(points) == 1: lat, lng = points[0] return [Waypoint(lat, lng, Route._get_country(lat, lng))] if src_country == dst_country: return [Waypoint(lat, lng, src_country) for lat, lng in points] else: m = len(points)/2 middle_country = Route._get_country(*points[m]) return _label_step(src_country, middle_country, points[:m]) \ + _label_step(middle_country, dst_country, points[m:]) return _label_step(city_from.country, city_to.country, points)
def main(): #test_pline = "fe_iGg{i|_@EIIMW[QUKIWWyIyH_]gZkVeTwAqA{BoBGGGIQSIKKO" #test_pline = "prwhGmer|_@oF?CjVHBDF@H`G?HA" cnf = handleArgs(); pline = open(cnf['polyline_file'], 'r').read() #pline = "djuhGect|_@AqK?SiAAiB?eB?e@G_@QYYi@k@MK@oDAmA" #pline = "djuhG{bt|_@?mFxE?TARATEVKd@YxAqA^OXEfGAhJ?zJ@zABpIDFGVAR?|BAxCGDBv@@nLAhG?|@??yC?mH?kCAOTAzAAhLK|IIbJCjf@MbD?f@C`CG~OUxAEp@A`@Bl@N\\Nh@d@nAvAlCzCbAfAb@\\FHB?FQHSDGHA@C^AZ?H?hDnBFHFHVXnF|C" #pline = "djuhGsct|_@AcK?SiAAiB?eB?e@G_@QYYi@k@w@o@" #pline = "djuhGect|_@?cFxE?TARATEVKd@YxAqA^OXE`@?|B??kI?oG?cH?wHxE?hBA`E@xC??`D?pLhA@|CErE?hD@HDxC?rLA`D?HEzCAtE?bGGvTS~b@MtNAnBClU_@p@Eh@?`@Dp@PXPf@f@lD~DtAzA^\\\\XHFL]HOJEl@AV?nDtBPTVV|BpA" json_data = getChchJsonData(cnf['json_file']) roadClosures = getRoadClosureToday(json_data) route = polyline.decode(pline) closed_blocks = getAllRoadsClosedOnTheRoute(roadClosures, route) print json.dumps(closed_blocks, sort_keys=True, indent=4)
def make_heat_map(data): threshold = session['threshold'] ts = [0.5, 1, 2, 5, 10, 20, 90] zs = [10, 10, 10, 5, 5, 1] #zoom 1 is all the way out zooms = dict(zip(ts, zs)) #zooms dictionary to get a proper zoom for a given threshold gmap = gmplot.GoogleMapPlotter(session['lat_med'], session['lon_med'], zooms[threshold]) heat_lats = [] heat_lons = [] for m in data.maps.values: summary_lat_lon = polyline.decode(m.summary_polyline) lats = [i[0] for i in summary_lat_lon] lons = [i[1] for i in summary_lat_lon] heat_lats.append(lats) heat_lons.append(lons) heat_lats = [val for sublist in heat_lats for val in sublist] heat_lons = [val for sublist in heat_lons for val in sublist] gmap.heatmap(heat_lats,heat_lons) output = StringIO() gmap.draw_file(output, session['gid']) return output.getvalue()
def export(trip_ids, no_waypoints=False, no_paths=False): kml = simplekml.Kml() for id in trip_ids: resp = requests.get(URL % id) data = resp.json() trip = data['trip'] waypoints = trip['waypoints'] legs = trip['legs'] if not no_paths: for leg in legs: ls = kml.newlinestring() ls.coords = [(c[1], c[0], 0.0) for c in polyline.decode(leg['encoded_polyline'])] ls.extrude = 1 ls.altitudemode = simplekml.AltitudeMode.clamptoground ls.style.linestyle.width = 5 ls.style.linestyle.color = simplekml.Color.cornflowerblue if not no_waypoints: for waypoint in waypoints: kml.newpoint(name=waypoint['name'], coords=[(waypoint['start_location'][0], waypoint['start_location'][1])]) if waypoint['start_location'][0] != waypoint['end_location'][0] or waypoint['start_location'][1] != waypoint['end_location'][1]: kml.newpoint(name=waypoint['name'], coords=[(waypoint['end_location'][0], waypoint['end_location'][1])]) kml.save('-'.join(trip_ids) + '.kml')
def test_a_variety_of_precisions(self): """uses a generator to create a variety of lat-lon's across the global and tests a range of precision settings from 4 to 8""" def generator(): while True: coords = [] for i in range(2, randint(4, 10)): lat, lon = uniform(-180.0, 180.0), uniform(-180.0, 180.0) coords.append((lat, lon)) yield coords patience = 3 # seconds. waypoints, okays = 0, 0 g = generator() start = time.time() while time.time() < start + patience: precision = randint(4, 8) wp = next(g) waypoints += len(wp) poly = polyline.encode(wp, precision) wp2 = polyline.decode(poly, precision) if wp == wp2: okays += len(wp2) else: for idx, _ in enumerate(wp): dx, dy = abs(wp[idx][0] - wp2[idx][0]), abs(wp[idx][1] - wp2[idx][1]) if dx > 10 ** -(precision - 1) or dy > 10 ** -(precision - 1): print("idx={}, dx={}, dy={}".format(idx, dx, dy)) else: okays += 1 assert okays == waypoints print("encoded and decoded {0:.2f}% correctly for {1} waypoints @ {2} wp/sec".format( 100 * okays / float(waypoints), waypoints, round(waypoints / patience, 0)))
def decode_coords(self, json, route_id, source_id=0): """ Parse the geometry from a json Parameters ---------- json : json-instance route_id : int source_id : int, optional(default=0) """ try: itinerary = json['plan']['itineraries'][0] except KeyError: return leg = itinerary['legs'][0] points = leg['legGeometry']['points'] coord_list = polyline.decode(points) route = self.routes.get_route(route_id, source_id) self.nodes.add_points(coord_list, route) if source_id not in self.areas: self.areas.add_area(source_id)
def test_decode_single_point(self): d = polyline.decode('gu`wFf`ys@') self.assertEqual(d, [ (40.641, -8.653) ])
def testgooglemaps(): poly_line = 'y}iyHthd@FT\\|@VXN`@j@hBl@nBFNCBPi@CMoG~E]TM?WE}@P{FzAuFxAaD~@}D|@oErAwA\\Q@gADkAIoAUo@[mAu@_@[[_@g@cAg@eBq@cDm@_Dc@}Dc@yHUeGOaFq@oUK_EUkDa@cEe@qDSaAgAyDeDqHiE_JcEsIeG{MiIsQkAgC_@kAEDh@`@BLo@f@[TDTRhBLfB@^OXk@dAIL' poly = polyline.decode(poly_line) return (poly)
import os import sqlite3 import polyline import mongo_conn as M from flask import Flask, render_template, jsonify app = Flask(__name__) unpolyline = lambda p: list(map(list, map(reversed, polyline.decode(p)))) @app.route('/') def index(): return render_template('index.html') @app.route('/data/<element>') def get_data(element): db = sqlite3.connect('Census Data/census.db').cursor() db.execute('SELECT ZCTA5, %s FROM zip_data' % element) data = {z[0]: z[1] for z in db.fetchall()} return jsonify(data) @app.route('/commutes/times/<work_zip>') def get_commute_times(work_zip): docs = list(M.aggregate_commute_times(work_zip)) zips = {z['zip']: z['duration'] for z in docs} total = sum([z['weight']*z['duration'] for z in docs]) /\ sum([z['duration'] for z in docs]) return jsonify({'zips': zips, 'total': total})
def update_path(self, origin_coord, dest_coord, waypoints): """ Returns a path between the origin coordinate and the destination coordinate, passing through a group of optional waypoints. origin_coord: A NumPy array [latitude, longitude] of the starting coordinate dest_coord: A NumPy array [latitude, longitude] of the destination coordinate waypoint: A NumPy array [n][latitude, longitude], where n<=10 Returns: A NumPy array [n][latitude, longitude], marking out the path. https://developers.google.com/maps/documentation/directions/start """ # set up URL url_head = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin_coord[0]},{origin_coord[1]}" \ f"&destination={dest_coord[0]},{dest_coord[1]}" url_waypoints = "" if len(waypoints) != 0: url_waypoints = "&waypoints=" if len(waypoints) > 10: print("Too many waypoints; Truncating to 10 waypoints total") waypoints = waypoints[0:10] for waypoint in waypoints: url_waypoints = url_waypoints + f"via:{waypoint[0]},{waypoint[1]}|" url_waypoints = url_waypoints[:-1] url_end = f"&key={self.api_key}" url = url_head + url_waypoints + url_end # HTTP GET r = requests.get(url) response = json.loads(r.text) path_points = [] # If a route is found... if response['status'] == "OK": print("A route was found.\n") # Pick the first route in the list of available routes # A route consists of a series of legs for leg in response['routes'][0]['legs']: # Every leg contains an array of steps. for step in leg['steps']: # every step contains an encoded polyline polyline_raw = step['polyline']['points'] polyline_coords = polyline.decode(polyline_raw) path_points = path_points + polyline_coords print("Route has been successfully retrieved!\n") else: print(f"No route was found: {response['status']}") print(f"Error Message: {response['error_message']}") route = np.array(path_points) # Removes duplicate coordinates to prevent gradient calculation errors if route.size != 0: duplicate_coordinate_indices = np.where( (np.diff(route[:, 0]) == 0)) and np.where( (np.diff(route[:, 1]) == 0)) route = np.delete(route, duplicate_coordinate_indices, axis=0) return route
routes_data = json.loads(routes.read().decode( routes.info().get_param('charset') or 'utf-8')) for route in routes_data: #print(route['id']) route_id = route['id'] routeDetailUrl = STRAVA_BASE_URL + STRAVA_URL_ROUTES_SLASH + str( route_id) + STRAVA_URL_ACCESS_TOKEN routes_detail = urllib.request.urlopen(routeDetailUrl) #api call data = json.loads(routes_detail.read().decode( routes_detail.info().get_param('charset') or 'utf-8')) routes_container.append(data) for route in routes_container: decoded_polyline = polyline.decode(route['map']['polyline']) route['strava_decoded_polyline'] = decoded_polyline origin = str(decoded_polyline[0][0]) + "," + str(decoded_polyline[0][1]) destination = str( decoded_polyline[len(decoded_polyline) - 1][0]) + "," + str( decoded_polyline[len(decoded_polyline) - 1][1]) route['google_traffic_data'] = [] for i in departure_times: google_maps_url = GOOGLE_MAPS_BASE_URL + origin + GOOGLE_MAPS_DESTINATION_URL + destination + GOOGLE_DEPARTURE_URL + str( i.time_asint) + GOOGLE_MAPS_KEY_URL + GOOGLE_MAPS_ACCESS_TOKEN google_maps_routes = urllib.request.urlopen(google_maps_url) valid_data = json.loads(google_maps_routes.read().decode( google_maps_routes.info().get_param('charset') or 'utf-8')) route['google_traffic_data'].append(valid_data)
def match_tripleg_with_publictransport(fromPlace, toPlace, trip_starttime, trip_endtime, all_recorded_trip_points): print("Input Trip ...:") print("trip_starttime:", trip_starttime) print("trip_endtime:", trip_endtime) tripmatchres = TripMatchedWithPlannerResult() # TODO TODO, who about these paratms returned by journey planner? # <walkTime>394</walkTime> # <transitTime>1020</transitTime> # <waitingTime>442</waitingTime> # <walkDistance>489.6903846194335</walkDistance> # <walkLimitExceeded>false</walkLimitExceeded> # <elevationLost>0.0</elevationLost> # <elevationGained>0.0</elevationGained> # <transfers>1</transfers> # returned by planner: # <tooSloped>false</tooSloped> recordedpoints = all_recorded_trip_points trip_starttime = trip_starttime.replace(microsecond = 0) trip_endtime = trip_endtime.replace(microsecond = 0) trip_duration = trip_endtime - trip_starttime # assumptions, constants, adjusting parameters, related cals, some kinematics, etc. -----------------: MAX_MODE_DETECTION_DELAY = 500 # (meters) we have latency in making sure of the mode change MAX_GPS_ERROR = 50 # (in meters) if error marger than this, we've discarded that point TODO ??? MAX_VEHICLE_LENGTH = 50 # TODO MAX_DISTANCE_FOR_POINT_MATCH = MAX_GPS_ERROR + MAX_VEHICLE_LENGTH #MAX_GPS_ERROR = 1000 # meters (somehow maxWalkDistance is equal to GPS error threshold for our system) # or maybe not... this could be also max_distance_between_busstops / 2 !! (if we have a detection between two bus stops) # 1000 m (e.g. 500 m walkking at each trip end) gives good results for user id 13 maxWalkDistance = MAX_MODE_DETECTION_DELAY * 2 # e.g. 500m walk to start bus stop ... 500m walk to end bus stop numItineraries = 3 # default is 3 maxTransfers = 2 # seems like this param didn't have any effect! showIntermediateStops = "True" # TODO: is there a param 'max waiting time' too? maxIntervals = {"bus":60, "tram":30, "train":60, "ferry":60} # max arrival interval of each public transport mode during working hours (minutes) maxSlowness = {"bus":3, "tram":3, "train":3, "ferry":5} # maximum slowness (a bit different concept than 'being late') of public transport (minutes) # we should note that being "slower"/"faster" is different than bus arrival being "late"/"early" # TODO! depends also on the city! in Helsinki it's sharp! :) ... in Rome, maybe not maxDError = MAX_MODE_DETECTION_DELAY * 2 # maximum Distance error (e.g: one deltaD at each end of the trip) legstartshift = timedelta(seconds = round(MAX_MODE_DETECTION_DELAY/minSpeeds['walk'])) # default: 4 minutes (*) or CALC: e.g: MAX_MODE_DETECTION_DELAY/minSpeeds['walk'] trip_starttime_earlier = trip_starttime - legstartshift print("legstartshift:",legstartshift) print("trip_starttime_earlier:", trip_starttime_earlier , " (note: WE'LL GIVE THIS TO JOURNEY PLANNER QUERY *)") print("") # query journey planner ----------: print("Query to journey planner:") # TODO: use Interface / Abstract class *: # later planner match for the whole finland*: https://api.digitransit.fi/routing/v1/routers/finland/ # later plannermatch for all possible countries: ??? OTP API interfance # ex: apiurl = IOTPServer.GetOTPAPIUrl() # shuld give the suitable instance, based on city/coutnry or user settings ... apiurl = 'http://api.digitransit.fi/routing/v1/routers/hsl/plan' querystr = "fromPlace={0}&toPlace={1}&date={2}&time={3}&numItineraries={4}&maxWalkDistance={5}&showIntermediateStops={6}" \ .format(fromPlace, toPlace, datetime.date(trip_starttime_earlier), datetime.time(trip_starttime_earlier), \ numItineraries, maxWalkDistance, showIntermediateStops); #ex: querystr = "fromPlace=60.170718,24.930221&toPlace=60.250214,25.009566&date=2016/4/22&time=17:18:00&numItineraries=3&maxTransfers=3&maxWalkDistance=1500" # ****** json_data = HttpRequestWithGet(apiurl, querystr) if 'plan' not in json_data or 'itineraries' not in json_data['plan']: #itineraries_count = len (json_data['plan']['itineraries']) #if itineraries_count == 0: # print "journey planner did NOT return any itineraries!\n" # print "json_data returned:\n", json_data, "\n" # print "json_data error section:\n", json_data['error'] if 'error' in json_data: return json_data['error']['id'], tripmatchres else: return 0, tripmatchres print("") print("Working on the routes suggested by journey planner ...:") itin_index = 0 matchcount = 0 plannedmatches = [] # go through all routes suggested ------ : for itin in json_data['plan']['itineraries']: duration = HSLDurationToNormalDuration(itin['duration']) # duration of planned trip starttime = HSLTimeStampToNormalDateTime(itin['startTime']) # start time of planned trip endtime = HSLTimeStampToNormalDateTime(itin['endTime']) # ... print("\n#", itin_index+1, ": This journey planner trip's duration, start & ends time: ", \ duration,"(",starttime , "-->", endtime,")\t")#, itin['duration'], " seconds", "(",itin['startTime'], itin['endTime'],")" # prepare the adjuster params TODO (instead of 'bus', it could be 'train', 'tram' ... depending on planned results) * maxdeltaW = timedelta(seconds = round(maxDError/minSpeeds['walk'])) # max acceptable diff, result of walking to the stop maxdeltaB = timedelta(seconds = round(maxDError/minSpeeds['bus'])) # max acceptable diff, result of bus traveling 1 stop less or more maxdeltaT = maxdeltaW + maxdeltaB maxI = timedelta(minutes = maxIntervals['bus']) # in minutes maxdeltaSlowness = timedelta(minutes = maxSlowness['bus']) # maxdeltaSlowness = timedelta(minutes = 0) # TODO !!!! temp. , remove this print("maxdeltaW, maxdeltaB, maxdeltaT, maxI: ", maxdeltaW, maxdeltaB, maxdeltaT, maxI, "maxdeltaB/2 + maxdeltaSlowness:",maxdeltaB/2 + maxdeltaSlowness) deltaT = abs(duration - trip_duration) deltaTsign = "" if duration < trip_duration: deltaTsign = "shorter" legsmatched = 0 legsreviewed = False # TODO: mostly for debugging # COND: pattern of planned trip-legs, # for example usually the idea is: 'WALK', <ride>, 'WALK' ... or WALK, RIDE (no ending walk) # there should not be more than 1 'ride' (mass_transit invehicle) trip-leg transitlegs_count = 0 for leg in itin['legs']: if leg['transitLeg']: transitlegs_count += 1 if transitlegs_count != 1: #TODO: support multi-leg match later asap! * print("number of planned transit legs:", transitlegs_count, " (should be 1) => ignoring this journey planner trip (!)") # COND: compare original trip's total duration WITH planned trip total duration elif duration < trip_duration and deltaT > maxdeltaSlowness: #TODO: ideally, maxdeltaSlowness should depend on current mode of transport print("original trip_duration:",trip_duration, "planned trip duration:", duration, "duration < trip_duration", " (deltaT:- ", deltaT,")", \ "=> how come planned trip is this much shorter than original trip ??!! => ignoring this journey planner trip (!)") # one reason could be: maybe the bus or tram ran faster this time! elif deltaT > maxdeltaT: print("original trip_duration:",trip_duration, "planned trip duration:", duration, "(deltaT:",deltaT,"maxdeltaT:",maxdeltaT,")", \ "=> too much difference! ignoring this journey planner trip (!)") else: # now look at legs of this itin to maybe find a match * legsreviewed = True print("Legs > > > > > > : ") planlegs = itin['legs'] legindex = 0 for leg in planlegs: matchedbytime = False matchedbyroute = False mode = leg['mode'] line = leg['route'] istransit = leg['transitLeg'] legduration = leg['duration'] legdurationnormal = HSLDurationToNormalDuration(int(legduration)) # TODO why int() ? legstarttime = HSLTimeStampToNormalDateTime(leg['startTime']) legendtime = HSLTimeStampToNormalDateTime(leg['endTime']) istransitstr = "" if istransit: istransitstr = " ***" # matching logic * (TODO >> also refer to paper notes, math equations, kinematics, assumptions, etc.) : # unavoidable delay in detections: our recorded point might be in between two bus stops (after the original origin bus stop and before 2nd or 3rd bus stop) # --> assume: person started the trip 1-2 minutes earlier # person started the trip ~500 meters before ridematched_str = "" if istransit: # COND: compare original-trip total duration WITH duration of planned transit-leg (bus, tram, etc) deltaTransitLeg = abs(trip_duration - legdurationnormal) if deltaTransitLeg <= maxdeltaB: # COND: planned start time not too far, e.g.: not more than bus interval deltaStarttime = abs(legstarttime - trip_starttime) deltaStartPassed = True if deltaStarttime > (maxdeltaB/2 + maxdeltaSlowness): deltaStartPassed = False if deltaStarttime > maxI: deltaStartPassed = False else: # matched with witch line_type? TRAM, SUBWAY, BUS, ...? matchedbytime = True # this leg is a match time-based * legsmatched += 1 ridematched_str = ":::::: this leg might be a match (time-based)!!" if not deltaStartPassed: print("planned trip-leg starts too late => ignoring this leg !!!") #END if is_transit #line name encoding, now considered utf-8 #TODO line_name_str = "None" if line: line_name_str = line.encode('utf-8') print(mode, line_name_str, ", is transit:", istransit, "| Duration: ", \ legdurationnormal, "(",legstarttime,"-->",legendtime,")", istransitstr, ridematched_str) matched_fraction = 0 longest_serialunmatch = 0 if matchedbytime and deltaStartPassed: # if this leg is matched (time-based), then # TODO refactor conditions #now check location-based print("") print("trying to match location-based as well ...") # TODO NOTICE! # there are so many bus and trams in city that for every car-ride there can be a similar bus/tram ride # how to solve this without live data ??!! # - with following filters? ex: avg-speed values # - matching recorded points "time" with intermediate-stop points "time"? # TODO # - give match score/priority to each matched leg # TODO # get geometry points from planned leg # match with some intermediate points of the filtered trip-leg we have here # ? how many point matches are enough? # recordedpoint_startindex = ... where deltastarttime ... => no. of skiprecordedpoints # recordedpoint_endindex = ... ignore the last ? N ? recorde points # step = (166)/(8,610/200) # step = (len(recordedpoints)) / (triplength_in_meters / 200) # # go to indexes according to step (plus always incluide the last point) (OR exclude the last point!!!) # exlude the points in the 'last minute'? # # do the matching loop # if N% of points do not have a match in plan ==> matching FAILED ? # if M consecutive points do not have a match in plan ==> matching FAILED ? # or mayve check both conditions ,, with OR # plannedpoints = polyline.decode(leg['legGeometry']['points']) # extract the recorded points which most probably are only the transit part ("good points") (B' section in paper notes) MIN_NUMBER_OF_GOODPOINTS = 4 # TODO *** print("Extracting the goodpoints from recorded points ...") prewalktime = timedelta(seconds=0) postwalktime = timedelta(seconds=0) if legindex>0: if planlegs[legindex-1]['mode'] == 'WALK': prewalktime = timedelta(seconds = planlegs[legindex-1]['duration']) prewalktime_to_ridetime = timedelta(seconds = planlegs[legindex-1]['distance']/minSpeeds['bus']) if legindex<len(planlegs)-1: if planlegs[legindex+1]['mode'] == 'WALK': postwalktime = timedelta(seconds = planlegs[legindex+1]['duration']) print("prewalktime:", prewalktime, "prewalktime_to_ridetime:", prewalktime_to_ridetime, "postwalktime:", postwalktime) print("recorded points (n=",len(recordedpoints),"):") goodpoints = [] hasgoodpoints = False start_recordedpoint = recordedpoints[0] end_recordedpoint = recordedpoints[len(recordedpoints)-1] recordedtrip_starttime = start_recordedpoint['time'] recordedtrip_endtime = end_recordedpoint['time'] for point in recordedpoints: point_location = json.loads(point["geojson"])["coordinates"] point_location_str='{1},{0}'.format(point_location[0],point_location[1]) point_time = point['time'] isgoodpoint = "---" # save this point only if its record time is within the range # and also consider enough distance between points moved = 0 n = len(goodpoints) if n > 0: previous_goodpoint = goodpoints[n-1] moved = point_distance(point, previous_goodpoint) if (point_time - recordedtrip_starttime) >= prewalktime_to_ridetime and (recordedtrip_endtime - point_time) >= postwalktime: if n > 0: if moved >= MAX_DISTANCE_FOR_POINT_MATCH: #TODO or after min 200 meters? goodpoints.append(point) isgoodpoint = "" else:# first detected good point: goodpoints.append(point) isgoodpoint = "" print(point_location_str, point_time, isgoodpoint, moved, "(m) moved since last goodpoint") #END loop .......... if len(goodpoints) >= MIN_NUMBER_OF_GOODPOINTS: hasgoodpoints = True else: print("not enough number of goodpoints extracted (no. of goodpoints=",len(goodpoints),"<",MIN_NUMBER_OF_GOODPOINTS,") !!!!!!") # COND 2 -------------------: if hasgoodpoints: goodtripdistance = point_distance(goodpoints[0], goodpoints[len(goodpoints)-1]) goodtripduration = goodpoints[len(goodpoints)-1]['time'] - goodpoints[0]['time'] if goodtripduration.total_seconds() > 0: goodtrip_avgspeed = goodtripdistance/goodtripduration.total_seconds() else: goodtrip_avgspeed = 0 print("@@ good part of recorded trip: d=", goodtripdistance, ", duration=",goodtripduration, ", goodtrip_avgspeed=", goodtrip_avgspeed) legdistance = leg['distance'] legduration = leg['duration'] if legduration > 0: legavgspeed = round(legdistance/legduration) else: legavgspeed = 0 legheadway = None if 'headway' in leg: legheadway = leg['headway'] print("@@ planned leg: d=", legdistance, ", duration=",timedelta(seconds=legduration), ", avg-speed=", legavgspeed, "headway:", legheadway) # TODO check distances , check average speeds, ... # COND1 -------------------: class PointMatchPair: point1 = None point2 = None MIN_MATCH_RATIO = 70 # (if 30%+ of recorded goodpoints don't have a match in plannedpoints, then routes do NOT match) MAX_SERIAL_UNMATCH = 4 # TODO, how to calculate this number??? ex: consider vehicle speed? if faster, then limit is 2 !? # when goodpoints are chosen with min 100 m distance => 4 serials = min 400 meters matchedpointpairs = [] unmatchedpoints = [] serialunmatches = [0] if hasgoodpoints: serialunmatchcount = 0 # number of consecutive goodpoints with no match in planned points print("Matching goodpoints n=",len(goodpoints)," with plannedpoints m=",len(plannedpoints), "...") # TODO make more efficient, make less than O(n^2) # traverse goodpoints and try to match each with a planpoint: for point in goodpoints: point_location = json.loads(point["geojson"])["coordinates"] point_location_str='{1},{0}'.format(point_location[0],point_location[1]) point_time = point['time'] # search for its match in planned points matchfound = False deltas = [] mindelta = MAX_DISTANCE_FOR_POINT_MATCH matchpair = PointMatchPair() for planpoint in plannedpoints: # traverse plannedpoints to find a match planpoint_reverse = planpoint[1],planpoint[0] delta = get_distance_between_coordinates(json.loads(point["geojson"])["coordinates"], planpoint_reverse) deltas.append(delta) if delta <= MAX_DISTANCE_FOR_POINT_MATCH: #found a match matchfound = True if delta <= mindelta: mindelta = delta matchpair.point1 = point matchpair.point2 = planpoint print("min delta for this goodpoint:", min(deltas)) if matchfound: matchedpointpairs.append(matchpair) if serialunmatchcount > 0: serialunmatches.append(serialunmatchcount) serialunmatchcount = 0 # reset else: unmatchedpoints.append(point) serialunmatchcount += 1 #END for, traverse goodpoints ----------- print("serialunmatches:", serialunmatches) matched_fraction = round( 100 * ( len(matchedpointpairs)/float(len(goodpoints)) ) ) longest_serialunmatch = max(serialunmatches) if matched_fraction >= MIN_MATCH_RATIO and longest_serialunmatch <= MAX_SERIAL_UNMATCH: matchedbyroute = True # this itin has a match also geoloc&route-based * ridematched_str = ":::::: this leg might be a match (time-based & route-based) !!" print("matched_fraction", matched_fraction, "%, MIN_MATCH_RATIO:", MIN_MATCH_RATIO,"%") print("longest_serialunmatch:",longest_serialunmatch, "points, MAX_SERIAL_UNMATCH:", MAX_SERIAL_UNMATCH) # TODO: just print for debug --------------------------------------- if LOG_DETAILS: print("@@@ printing recorded points (n=",len(recordedpoints),"): ") for point in recordedpoints: point_location = json.loads(point["geojson"])["coordinates"] point_location_str='{1},{0}'.format(point_location[0],point_location[1]) print(point_location_str) print("@@@ printing goodpoints (n=",len(goodpoints),"): ") for point in goodpoints: point_location = json.loads(point["geojson"])["coordinates"] point_location_str='{1},{0}'.format(point_location[0],point_location[1]) print(point_location_str) print("@@@ printing planned trip (n=",len(plannedpoints),"):") for point in plannedpoints: point_location = point point_location_str='{0},{1}'.format(point_location[0],point_location[1]) print(point_location_str) intermstops = leg['intermediateStops'] print("@@@ printing intermediate stops of planned trip (n=",len(intermstops),"):") for stop in intermstops: stopname = stop['name'].encode('utf-8') print("stop[{3}][{4}]: {0}, @{1} .. @{2}".format(stopname, \ HSLTimeStampToNormalDateTime(stop['arrival']), HSLTimeStampToNormalDateTime(stop['departure']), \ stop['stopIndex'], stop['stopSequence'])) print("@@@ matched goodpoints (n=",len(matchedpointpairs),"):") for pointpair in matchedpointpairs: point = pointpair.point1 point_location = json.loads(point["geojson"])["coordinates"] point_location_str1='{1},{0}'.format(point_location[0],point_location[1]) point = pointpair.point2 point_location = point point_location_str2='{0},{1}'.format(point_location[0],point_location[1]) point_location_str='{0} --> {1}'.format(point_location_str1, point_location_str2) print(point_location_str) print("@@@ unmatched goodpoints (n=",len(unmatchedpoints),"):") for point in unmatchedpoints: point_location = json.loads(point["geojson"])["coordinates"] point_location_str='{1},{0}'.format(point_location[0],point_location[1]) print(point_location_str) if matchedbytime: #and matchedbyroute: # save this leg as a match * # TODO!!! check both! matchcount += 1 # number of total matches found so far (among all planned itins) plannedmatch = PlannedTrip() # a new matched planned trip #these value comes from the itin itself, not from this leg:: plannedmatch.start = starttime plannedmatch.end = endtime plannedmatch.deltaT = deltaT plannedmatch.deltaTsign = deltaTsign #these value comes from this matched leg:: plannedmatch.linetype = mode plannedmatch.linename = line plannedmatch.legstart = legstarttime plannedmatch.legend = legendtime plannedmatch.deltaStarttime = deltaStarttime if legstarttime < trip_starttime: plannedmatch.deltaStarttimeStr = ("-{0}").format(deltaStarttime) # planned transitleg starts earlier than recorded starttime else: plannedmatch.deltaStarttimeStr = ("+{0}").format(deltaStarttime) # planned transitleg starts later or same time plannedmatch.deltaStartPassed = deltaStartPassed plannedmatch.matchedbytime = matchedbytime plannedmatch.matchedbyroute = matchedbyroute plannedmatch.matched_fraction = matched_fraction plannedmatch.longest_serialunmatch = longest_serialunmatch # TODO: also save ??? will be useful??: # legloc start, end # leg geo points plannedmatches.append(plannedmatch) #END IF --- legindex += 1 #LOOP END -- traverse next leg of current itin #else END # --- alll legs of current itin has been traveresed up to this point # assumption for now: only 1 trip-leg (transit leg) from each planned itin can be a match # TODO: support multi-leg matches later asap *!! if legsmatched > 0: # we've found transit-leg(s) as a match in this itin (ideally should be only 1 matched leg (the only transit leg)) #planned_start.append(starttime) #planned_end.append(endtime) donothing = None # TODO if not legsreviewed: # TODO *** print("Legs > > > > > > : ") for leg in itin['legs']: mode = leg['mode'] line = leg['route'] istransit = leg['transitLeg'] legduration = leg['duration'] legdurationnormal = HSLDurationToNormalDuration(int(legduration)) # TODO why int() ? legstarttime = HSLTimeStampToNormalDateTime(leg['startTime']) legendtime = HSLTimeStampToNormalDateTime(leg['endTime']) #line name encoding, now considered utf-8 #TODO line_name_str = "None" if line: line_name_str = line.encode('utf-8') print(mode, line_name_str, ", is transit:", istransit, "| Duration: ", \ legdurationnormal, "(",legstarttime,"-->",legendtime,")") itin_index += 1 # LOOP END --- traverse next planned itin print("") print("from all planned itins ==>") print("matchcount:", matchcount) bestmatchindex = 0 # refining the matched legs from all planned itins, choosing the best match: # assumption: HSL journey planner returns the best match first! if len(plannedmatches)>0: print("Refining the matched planned trips ...") min_deltaStarttime = plannedmatches[0].deltaStarttime matchindex = 0 for match in plannedmatches: print("[",matchindex,"]: match.deltaStarttime:", match.deltaStarttime) if match.deltaStarttime < min_deltaStarttime: min_deltaStarttime = plannedmatches[matchindex].deltaStarttime bestmatchindex = matchindex matchindex += 1 print("bestmatchindex:", bestmatchindex) if len(plannedmatches)>0: tripmatchres.trip = plannedmatches[bestmatchindex] tripmatchres.bestmatchindex = bestmatchindex tripmatchres.matchcount = matchcount return 1, tripmatchres else: return 1, tripmatchres
def decodepolyline(polyline): line = decode(polyline) out_list = [] for point in line: out_list.append({'loc': {'lat': point[1], 'lng': point[0]}}) return out_list
# parameters required - Google Maps API key, then workout description, then author name key = sys.argv[1] getdesc = sys.argv[2] author = sys.argv[3] # retrieve the necessary information from the sqlite database conn = sqlite3.connect( 'stt.db') # place the sports-tracker database in the current directory c = conn.cursor() # select the necessary data from the given record c.execute( 'SELECT polyline, startTime, totalTime FROM workoutheader WHERE description = "' + getdesc + '"') # just fetch the first one - if multiple for given workout description, should change logic to select on id instead vals = c.fetchone() coords = polyline.decode( vals[0]) # convert polyline into array of lat/lon coordinates trktime = datetime.datetime.fromtimestamp( vals[1] / 1e3) # convert startTime to a python datetime # calculate the millisecond delta by dividing the total workout time by the number of track points delta = int(vals[2] * 1e3 / len(coords)) # set up for calls to Google Maps API url = 'https://maps.googleapis.com/maps/api/elevation/json?key=' + key + '&locations=' # create an XML document in the sports-tracker format... gpx = ET.Element('gpx') metadata = ET.SubElement(gpx, 'metadata') name = ET.SubElement(metadata, 'name') desc = ET.SubElement(metadata, 'desc') author = ET.SubElement(metadata, 'author') aname = ET.SubElement(author, 'name')
def get_route(api_key: str, start: Union[str, tuple], end: str, start_time: str, speed: int, output_interval: int) -> Tuple[datetime.datetime, LatLng]: google_client = googlemaps.Client(api_key) today: datetime.datetime = datetime.datetime.strptime( start_time, '%Y/%m/%d %H:%M') response: List = [] try: response = google_client.directions(origin=start, destination=end, language="ja", mode="driving", avoid=["indoor"]) except Exception as ex: print(sys.exc_info(), ex) return today, LatLng(0, 0) # 経路情報を取得 steps: List = response[0]["legs"][0]["steps"] # パスを構築する path_points = [] for stp in steps: points: str = stp["polyline"]["points"] lat_lngs = polyline.decode(points) for lat_lng in lat_lngs: # 緯度・経度のタプル path_points.append(LatLng(*lat_lng)) # 区間を構築 new_steps = [] length = len(path_points) distance = 0.0 # 次のポイントと組み合わせて区間を構築 for i in range(0, length - 1): bgn_point = path_points[i] end_point = path_points[i + 1] # 2点間の距離・差分などを計算 section_distance = calc_distance(bgn_point, end_point) end_distance = distance + section_distance # 名前付きタプルを構築 obj = SectionInfo(bgn_point, end_point, section_distance, end_point - bgn_point, distance, end_distance) new_steps.append(obj) # 全走行距離を計算 distance += section_distance # シミュレート開始 # 時速何km/hが秒速で何m進むか car_speed = (speed * 1000.0) / 3600.0 # 全行程距離(m)を所定の秒速なら何秒で終了するか loop_count: int = int(distance / car_speed) # 車の位置 car_pos: float = 0.0 time_delta: datetime.timedelta = datetime.timedelta(seconds=1) new_car_pos: LatLng = new_steps[0].end # ループ開始(分解能は1秒) for x in range(0, loop_count): for i in range(0, len(new_steps)): step: SectionInfo = new_steps[i] # 現在車の距離がどの区間にあるのか判定する if step.bgn_distance <= car_pos <= step.end_distance: # 区間の距離 section_distance = step.distance # 区間の開始位置から車の距離 car_pos_from_bgn = car_pos - step.bgn_distance # 区間内において、車の位置が何%の位置にあるのかを計算 car_progres_per = car_pos_from_bgn / section_distance # 開始・終点の傾き * 区間内の位置 new_car_pos = step.bgn + step.delta * car_progres_per # 3秒単位で出力 if x % output_interval == 0: print( '%s,%3.32f,%3.32f,%d,"%s","%s"' % (today.strftime('%Y/%m/%d %H:%M:%S'), new_car_pos.lat, new_car_pos.lng, speed, start, end)) break today += time_delta # 車の移動 car_pos += car_speed # print("全長", distance) return today, new_car_pos
def decode_polyline(self): return polyline.decode(self.polyline)
import pickle import numpy as np import polyline from intersection import num_self_intersections f = open("requests.pickle", "rb") data = [r for r in pickle.load(f) if r["statistics_data"]["input_length"] > 0] TIME_UNIT = "usec" SHUFFLE_CONSTANT = 0.000001 statistics_data = [r["statistics_data"] for r in data] print("Decoding...") routes = [polyline.decode(r["route_geometry"]) for r in data] sketches = [polyline.decode(r["schematized_geometry"]) for r in data] more_intersections = 0 less_intersections = 0 same_intersections = 0 less_diffs = [] more_diffs = [] print("Testing intersection..") for r, s in zip(routes, sketches): num_r = num_self_intersections(r) num_s = num_self_intersections(s) if num_r == num_s: same_intersections += 1
def get_track(polyline_data): coords = polyline.decode(polyline_data) coords = [(x, y) for (y, x) in coords] if len(coords) == 1: coords = [] return MultiLineString([LineString(coords, srid=4326)], srid=4326)
connection = engine.connect() es = Elasticsearch([config['elasticsearch']['host']]) index = "listings" doc_type = "route" """ Fetch all jobs """ for job in fetch_pending(connection): overview_path = job['overview_path'] id = job['id'] listing_id = job['fk_listing_id'] docs = [] mark_in_progress(id, connection) path = polyline.decode(overview_path) # We grabbed the jobs, save geospatial data to elasticsearch for point in path: # we need to invert these points to follow the GeoJSON format formatted_point = [point[1], point[0]] action = { "_index": "listings", "_type": "route", "_source" : { "listing_id": listing_id, "location": formatted_point } } docs.append(action)
def mapview(): pokemons = [ [33.678, -116.243], [33.679, -116.244], [33.680, -116.250], [33.681, -116.239], [33.678, -116.289] ] # polyline = {} # polyline['stroke_weight'] = 20 # polyline['stroke_opacity'] = 1.0 # polyline['stroke_color'] = '#0AB0DE' # polyline['path'] = [{'lat':00.00}, {'lng':-50.000}, {'lat':50.00, 'lng':60.00}] # path1 = [(24.532, -123.43), (62.34, -12.34), (-34.23, 53.23), (34.23, -12.53)] pokemarkers = [] for pokemon in pokemons: pokemarkers.append({ 'lat': pokemon[0], 'lng': pokemon[1] }) polyline = { 'stroke_color': '#0AB0DE', 'stroke_opacity': 1.0, 'stroke_weight': 3, } directions_url = 'https://maps.googleapis.com/maps/api/directions/json' params = {} # params['origin'] = 'Disneyland' params['origin'] = coord_to_str(pokemons[0]) params['destination'] = coord_to_str(pokemons[len(pokemons) - 1]) params['waypoints'] = waypoints_to_str(pokemons[1:len(pokemons) - 1]) params['key'] = API_KEY r = requests.get(directions_url, params=params, verify=False) json = r.json() # print("DIRECTIONS", json) print("DIRECTIONS") print(json) print(json['routes'][0]['overview_polyline']['points']) overview_polyline = pl.decode(json['routes'][0]['overview_polyline']['points']) print(overview_polyline) optimal_path = [] for coord in overview_polyline: optimal_path.append({'lat':coord[0] ,'lng':coord[1]}) # print(len(json['routes'][0]['legs'])) polyline['path'] = optimal_path plinemap = Map( identifier="plinemap", style=( "height:100%;" "width:100%;" "top:0;" "left:0;" "position:absolute;" "z-index:200;" ), lat=33.678, lng=-116.243, markers=pokemarkers, polylines=[polyline] ) return render_template( 'example.html', plinemap=plinemap )
#route_list = [] payload = {'valueInputOption': 'RAW', 'data': []} payload_links = {'valueInputOption': 'USER_ENTERED', 'data': []} rownumber = 1 for x in route_list: rownumber += 1 url = f"https://www.strava.com/api/v3/routes/{x}" print(url) r = requests.get(url + '?access_token=' + strava_tokens['access_token']) input_json = r.json() payload['data'].append({ 'range': f"B{rownumber}", 'values': [[input_json['name']]] }) map_poly = polyline.decode(input_json['map']['polyline']) waypoint_diff = len(map_poly) / 8 waypoint_id = int(waypoint_diff) waypoints = [] while waypoint_id < (len(map_poly) - int(waypoint_diff)): waypoints.append( f"{map_poly[waypoint_id][0]},{map_poly[waypoint_id][1]}") waypoint_id += int(waypoint_diff) payload_links['data'].append({ 'range': f"C{rownumber}", 'values': [[ f'=HYPERLINK("https://www.google.com/maps/dir/?api=1&origin={map_poly[0][0]},{map_poly[0][1]}&destination={map_poly[-1][0]},{map_poly[-1][1]}&travelmode=bicycling&waypoints={"%7C".join(waypoints)}", "Google")' ]] }) payload['data'].append({
def run(self): """Run method that performs all the real work""" # show the dialog self.dlg.show() # Run the dialog event loop dialog = QProgressDialog() dialog.setWindowTitle("Best Eatery Progress") dialog.setLabelText("...") bar = QProgressBar(dialog) bar.setTextVisible(True) bar.setMaximum(100) bar.setValue(0) dialog.setBar(bar) dialog.setMinimumWidth(300) dialog.show() result = self.dlg.exec_() # See if OK was pressed if result: city= self.dlg.lineEdit.text() dish= self.dlg.lineEdit_3.text() location= self.dlg.lineEdit_2.text() price_min= int(self.dlg.lineEdit_4.text()) price_max= int(self.dlg.lineEdit_5.text()) bar.setValue(10) class_obj= best_restaurant(city,location,dish,price_min,price_max) checker=class_obj.shortner() if (checker==True): best_restaurants=class_obj.data_extractor(dish,price_min,price_max) bar.setValue(50) user_coords=class_obj.user_location() best_restaurant_loc= class_obj.best_retaurants_location(best_restaurants,user_coords) bar.setValue(60) final_restaurant=class_obj.distance_finder(best_restaurant_loc,user_coords) fin=final_restaurant[0] bar.setValue(70) direction_route_points=class_obj.directions_finder(user_coords,final_restaurant) direction_route=polyline.decode(direction_route_points) bar.setValue(80) direction_wkt=class_obj.shapefile_creator_multiline(direction_route) user_point=class_obj.user_wkt(user_coords) restaurant_point=class_obj.restaurant_wkt(final_restaurant) bar.setValue(90) # temp=QgsVectorLayer() temp = QgsVectorLayer("MULTILINESTRING?crs=epsg:4326", "Route", "memory") QgsProject.instance().addMapLayer(temp) temp.startEditing() geom = QgsGeometry() geom = QgsGeometry.fromWkt(direction_wkt) feat = QgsFeature() feat.setGeometry(geom) temp.dataProvider().addFeatures([feat]) temp.commitChanges() p1=QgsVectorLayer() p1=QgsVectorLayer("POINT?crs=epsg:4326", "User", "memory") QgsProject.instance().addMapLayer(p1) p1.startEditing() g=QgsGeometry() g=QgsGeometry.fromWkt(user_point) f=QgsFeature() f.setGeometry(g) p1.dataProvider().addFeatures([f]) p1.commitChanges() p2=QgsVectorLayer() p2=QgsVectorLayer("POINT?crs=epsg:4326", fin, "memory") QgsProject.instance().addMapLayer(p2) p2.startEditing() g1=QgsGeometry() g1=QgsGeometry.fromWkt(restaurant_point) f1=QgsFeature() f1.setGeometry(g1) p2.dataProvider().addFeatures([f1]) p2.commitChanges() bar.setValue(100) message="The Best Restaurant I Found is " +fin MessageBar = iface.messageBar().createMessage(message) iface.messageBar().pushWidget(MessageBar, Qgis.Info) elif(checker==False): rest=class_obj.all_restaurants() bar.setValue(20) r=class_obj.restaurant_urls(rest) bar.setValue(30) dish_per_restaurant=class_obj.dish_per_res(r,rest) bar.setValue(40) class_obj.database_writer(rest,dish_per_restaurant) best_restaurants=class_obj.data_extractor(dish,price_min,price_max) bar.setValue(50) user_coords=class_obj.user_location() best_restaurant_loc= class_obj.best_retaurants_location(best_restaurants,user_coords) bar.setValue(60) final_restaurant=class_obj.distance_finder(best_restaurant_loc,user_coords) fin=final_restaurant[0] bar.setValue(70) direction_route_points=class_obj.directions_finder(user_coords,final_restaurant) direction_route=polyline.decode(direction_route_points) bar.setValue(80) direction_wkt=class_obj.shapefile_creator_multiline(direction_route) user_point=class_obj.user_wkt(user_coords) restaurant_point=class_obj.restaurant_wkt(final_restaurant) bar.setValue(90) # temp=QgsVectorLayer() temp = QgsVectorLayer("MULTILINESTRING?crs=epsg:4326", "Route", "memory") QgsProject.instance().addMapLayer(temp) temp.startEditing() geom = QgsGeometry() geom = QgsGeometry.fromWkt(direction_wkt) feat = QgsFeature() feat.setGeometry(geom) temp.dataProvider().addFeatures([feat]) temp.commitChanges() p1=QgsVectorLayer() p1=QgsVectorLayer("POINT?crs=epsg:4326", "User", "memory") QgsProject.instance().addMapLayer(p1) p1.startEditing() g=QgsGeometry() g=QgsGeometry.fromWkt(user_point) f=QgsFeature() f.setGeometry(g) p1.dataProvider().addFeatures([f]) p1.commitChanges() p2=QgsVectorLayer() p2=QgsVectorLayer("POINT?crs=epsg:4326", fin, "memory") QgsProject.instance().addMapLayer(p2) p2.startEditing() g1=QgsGeometry() g1=QgsGeometry.fromWkt(restaurant_point) f1=QgsFeature() f1.setGeometry(g1) p2.dataProvider().addFeatures([f1]) p2.commitChanges() bar.setValue(100) message="The Best Restaurant I Found is " +fin MessageBar = iface.messageBar().createMessage(message) iface.messageBar().pushWidget(MessageBar, Qgis.Info) # Do something useful here - delete the line containing pass and # substitute with your code. pass
import polyline file = open('polyline.txt', 'r') polyline = file.readline() print polyline polyline.decode(polyline)
], [ '{vnsIeqlkAnAh@\\aD[M_D{A', '{vnsIeqlkAnAh@\\aD[MmN}GwDaBmAe@', '{vnsIeqlkAnAh@cA`Ke@zE', '{vnsIeqlkAnAh@YvC', '{vnsIeqlkAnAh@cA`Kw@bIWhE@~@Fr@JxC?lC?ZP@v@Ll@Th@ZVVTJPRl@p@dEtErA~ApA_Nb@gE', '{vnsIeqlkAnAh@\\aDtKzE|G|C', [] ] ] polylines = [] for i in range(len(polylines_string)): polylines.append([]) for j in range(len(polylines_string)): if polylines_string[i][j] != '': polylines[i].append(polyline.decode(polylines_string[i][j])) def map_plot(idx, d): line_coords = list( map(lambda i: polylines[i[0]][i[1]], list(zip(idx[:-1], idx[1:])))) # Features to draw on the map lines = [] markers = [] for points in line_coords: for p1, p2 in zip(points[:-1], points[1:]): lines.append(gmaps.Line(start=p1, end=p2, stroke_weight=3.0)) for i, p in enumerate(map(lambda x: candidate_stops[x], idx)):
import polyline from ast import literal_eval as make_tuple import geojson from geojson import MultiLineString, Feature, FeatureCollection _, data = open("part-00000").read().strip().split('\t') segments, score = make_tuple(data) segcoords = [] for seg in segments: line = polyline.decode(seg[2]) segcoords.append(line) connectors = [] for i in range(len(segments)): connection = [] connection.append(segments[i][1]) connection.append(segments[(i + 1) % len(segments)][0]) connectors.append(connection) #geojson format wants coords to be swapped segcoords = [[(c[1], c[0]) for c in seg] for seg in segcoords] connectors = [[(c[1], c[0]) for c in con] for con in connectors] linestring = MultiLineString(segcoords) connectorstring = MultiLineString(connectors) feature = Feature(geometry=linestring) connectorfeature = Feature(geometry=connectorstring) features = FeatureCollection([feature, connectorfeature]) json = geojson.dumps(features)
def get_directions(start: Union[str, dict, list, tuple], end: Union[str, dict, list, tuple]) -> dict: """ Query distances API from Google Maps to compute route from start to end. Args: - START (Union[string, dict, list tuple]) - E.g. a string of a place or its GPS coordinates. - END (Union[string, dict, list tuple]). E.g. a string of a place or its GPS coordinates. Returns: - DIRECTIONS (dict) - Keys are transportation modes, values are: - distance: a dict consisting of modes and distances. - duration: a dict consisting of modes and distances. - coordinates: a list of GPS coordinates. """ directions = dict() for mode in ['driving', 'walking', 'bicycling', 'transit']: routes = GMAPS.directions(start, end, mode=mode, departure_time=datetime.now()) # Skip this transportation type if no route is available if len(routes) == 0: continue # Allocate dict directions[mode] = dict() directions[mode]['distance'] = dict() directions[mode]['duration'] = dict() directions[mode]['coordinates'] = [] # Gather data (parse individual parts of the journey) for step in routes[0]['legs'][0]['steps']: # Parse the polyline into GPS coordinates directions[mode]['coordinates'].extend( polyline.decode(step['polyline']['points'])) # Update the distance and duration values # travel_mode defaults to what is given in step directly, but the # nesting is necessary to separate transit modes (Bus, Tram etc.) travel_mode = step.get('transit_details', {}).get('line', {}).get( 'vehicle', {}).get('type', step['travel_mode']).lower() directions[mode]['duration'].update({ travel_mode: ( directions[mode]['duration'].get(travel_mode, 0) + step['duration']['value'] ) }) # yapf: disable directions[mode]['distance'].update({ travel_mode: ( directions[mode]['distance'].get(travel_mode, 0) + step['distance']['value'] ) }) # yapf: disable return directions
s.save() client = StravaIO(access_token=s.settings['token']['access_token']) athlete = client.get_logged_in_athlete() athlete.store_locally() list_activities = client.get_logged_in_athlete_activities(after='1 september') # Obvious use - store all activities locally for a in list_activities: activity = client.get_activity_by_id(a.id) activity.store_locally() #pprint(activity.to_dict()) line = activity.to_dict()['map']['polyline'] #print(line) points = polyline.decode(line) #pprint(points) if len(points) > 0: break r = Route(line) print(r) r.normalize() print(r) # LAT_INDEX = 0 # LNG_INDEX = 1 # lats = [p[LAT_INDEX] for p in points] # lngs = [p[LNG_INDEX] for p in points] # minlat = min(lats)
import random from gmplot import gmplot #In the terminal, run "export TOKEN=(insert_your_strava_api_key)" token = os.environ["TOKEN"] headers = {'Authorization': "Bearer {0}".format(token)} segments = requests.get( "https://www.strava.com/api/v3/athlete/activities?page={0}".format(1), headers=headers) seg_json = segments.json() paths = [] for segment in seg_json: encoded_coords = segment['map']['summary_polyline'] if encoded_coords != None: paths.append(polyline.decode(encoded_coords)) def find_center(single_run): total_lats = 0 total_lngs = 0 counter = 0 for coord in single_run: total_lats += coord[0] total_lngs += coord[1] counter += 1 center = (total_lats / counter, total_lngs / counter) return (center) # Place map
def _get_directions_points(self): points = [] for point in self._directions_encoded_points: points += polyline.decode(point) return [x for n, x in enumerate(points) if x not in points[:n]]
def make_polyline_dict(recommend_dict): '''Take in a dictionary of map objects and return dictionary of polylines{index:polyline} and the indices for the polylines as a list.''' polylines = {} for k, v in recommend_dict.items(): v = ast.literal_eval(v) if v['summary_polyline'] != None: #make sure the polyline list isn't empty polylines[k] = v['summary_polyline'] indices = list(polylines.keys()) return polylines, indices #make list of coordinate lists polylines = make_polyline_dict(recommendations) map_coordinates = [] for line in polylines: coordinates = polyline.decode(line) map_coordinates.append(coordinates) #make unique route list def find_centroids(coordinate_lst): centroids = [] for l in coordinate_lst: lats = [] longs = [] for point in l: lats.append(point[0]) longs.append(point[1]) centroid = (round(np.mean(lats), 3), round(np.mean(longs), 3)) centroids.append(centroid) return centroids
def decode(string): return polyline.decode(string)
def mapping(self, start, end, dis, arg): gmaps = googlemaps.Client( key='AIzaSyBjcH8wXlR_EZAIm8k8XFHgkJ6cOlEtpvM') now = datetime.now() directions_result = gmaps.directions(start, end, mode="driving", departure_time=now) DirectionResult = directions_result[0]['legs'] DirectionSteps = DirectionResult[0]['steps'] DecodedNp = np.zeros(shape=[1, 2]) for step in DirectionSteps: Temp = list(step['polyline'].values()) DecodedNp = np.concatenate( (DecodedNp, np.array(polyline.decode(Temp[0])))) DecodedPos = DecodedNp.tolist() m = folium.Map(location=DecodedPos[1], zoom_start=5, tiles="Stamen Toner") draw = Draw() draw.add_to(m) #folium.TileLayer('Mapbox Control Room').add_to(m) # 여러가지 타일들 "Mapbox Bright" #folium.TileLayer('Stamen Toner').add_to(m) #folium.TileLayer('openstreetmap').add_to(m) #folium.LayerControl().add_to(m) # 빠른 마커로딩과 동시에 안됨 convert_dis = dis try: convert_dis = float(convert_dis) except ValueError: pass if arg == 1: if convert_dis * 1000 < DirectionResult[0]['distance']['value']: folium.Circle(location=DecodedPos[1], popup='Available distance', radius=convert_dis * 1000, color='#8AC317', fill=True, fill_color='#BBFF33').add_to(m) #기본 길이단위 미터 ShortestPolyline = folium.PolyLine(locations=[DecodedPos[1:]], color='red', weight=5).add_to(m) attr = { 'fill': '#421100', 'font-weight': 'bold', 'font-size': '48' } folium.plugins.PolyLineTextPath(ShortestPolyline, text='\u00BB ', repeat=True, center=True, offset=16, attributes=attr).add_to( m) # 색깔 그림 폰트 등등 라인꾸미기 self.progressBar.setValue(50) elif arg == 2: folium.Circle(location=DecodedPos[1], popup='Available distance', radius=convert_dis * 1000, color='#8AC317', fill=True, fill_color='#BBFF33').add_to(m) #기본 길이단위 미터 self.progressBar.setValue(0) EV_data = self.EV_Discovery() Availiable_ChargerLocList = [] for i in range(len(EV_data)): Charger_distance = self.Distance(DecodedPos[1][0], DecodedPos[1][1], EV_data[i][0], EV_data[i][1]) if Charger_distance < convert_dis: Availiable_ChargerLocList.append(EV_data[i]) folium.plugins.FastMarkerCluster(Availiable_ChargerLocList).add_to( m) if len(Availiable_ChargerLocList) == 0: self.textBrowser.append("There are no availiable charger") self.progressBar.setValue(100) elif arg == 3: folium.Circle(location=DecodedPos[1], popup='Available distance', radius=convert_dis * 1000, color='#8AC317', fill=True, fill_color='#BBFF33').add_to(m) #기본 길이단위 미터 self.progressBar.setValue(0) EV_data = self.EV_Discovery() Availiable_ChargerLocList = [] for i in range(len(EV_data)): Charger_distance = self.Distance(DecodedPos[1][0], DecodedPos[1][1], EV_data[i][0], EV_data[i][1]) if Charger_distance < convert_dis: Availiable_ChargerLocList.append(EV_data[i]) print(len(Availiable_ChargerLocList)) if len(Availiable_ChargerLocList) == 0: if convert_dis * 1000 < DirectionResult[0]['distance']['value']: folium.Circle(location=DecodedPos[1], popup='Available distance', radius=convert_dis * 1000, color='#8AC317', fill=True, fill_color='#BBFF33').add_to(m) #기본 길이단위 미터 ShortestPolyline = folium.PolyLine(locations=[DecodedPos[1:]], color='red', weight=5).add_to(m) attr = { 'fill': '#421100', 'font-weight': 'bold', 'font-size': '48' } folium.plugins.PolyLineTextPath(ShortestPolyline, text='\u00BB ', repeat=True, center=True, offset=16, attributes=attr).add_to( m) # 색깔 그림 폰트 등등 라인꾸미기 self.progressBar.setValue(50) self.textBrowser.append("There are no availiable charger") else: self.progressBar.setValue(70) #Find Efficient Electric Charger location min_Dist = 10000000000 # Initial min value Efficient_ElecChargLoc = [] for i in range(len(Availiable_ChargerLocList)): Dist1 = self.Distance(DecodedPos[1][0], DecodedPos[1][1], Availiable_ChargerLocList[i][0], Availiable_ChargerLocList[i][1]) Dist2 = self.Distance(DecodedPos[-1][0], DecodedPos[-1][1], Availiable_ChargerLocList[i][0], Availiable_ChargerLocList[i][1]) if (Dist1 + Dist2 < min_Dist): min_Dist = Dist1 + Dist2 Efficient_ElecChargLoc = [ Availiable_ChargerLocList[i][0], Availiable_ChargerLocList[i][1] ] print(Efficient_ElecChargLoc) self.progressBar.setValue(80) folium.Marker(Efficient_ElecChargLoc, popup='Recommended Electric Charger', icon=folium.Icon(color='green')).add_to(m) reverse_geocode_result = gmaps.reverse_geocode( Efficient_ElecChargLoc) ElecLocStr = reverse_geocode_result[0]['formatted_address'] #Start to Electric charger directions_result = gmaps.directions(start, ElecLocStr, mode="driving", departure_time=now) DirectionResult = directions_result[0]['legs'] DirectionSteps = DirectionResult[0]['steps'] DecodedNp = np.zeros(shape=[1, 2]) for step in DirectionSteps: Temp = list(step['polyline'].values()) DecodedNp = np.concatenate( (DecodedNp, np.array(polyline.decode(Temp[0])))) DecodedPos = DecodedNp.tolist() StartToElecCharg = folium.PolyLine(locations=[DecodedPos[1:]], color='green', weight=5).add_to(m) attr = { 'fill': '#421100', 'font-weight': 'bold', 'font-size': '48' } folium.plugins.PolyLineTextPath(StartToElecCharg, text='\u00BB ', repeat=True, center=True, offset=16, attributes=attr).add_to( m) # Color, font #Electric charger to end directions_result = gmaps.directions(ElecLocStr, end, mode="driving", departure_time=now) DirectionResult = directions_result[0]['legs'] DirectionSteps = DirectionResult[0]['steps'] DecodedNp = np.zeros(shape=[1, 2]) for step in DirectionSteps: Temp = list(step['polyline'].values()) DecodedNp = np.concatenate( (DecodedNp, np.array(polyline.decode(Temp[0])))) DecodedPos = DecodedNp.tolist() ElecChargToEnd = folium.PolyLine(locations=[DecodedPos[1:]], color='green', weight=5).add_to(m) attr = { 'fill': '#421100', 'font-weight': 'bold', 'font-size': '48' } folium.plugins.PolyLineTextPath(ElecChargToEnd, text='\u00BB ', repeat=True, center=True, offset=16, attributes=attr).add_to( m) # 색깔 그림 폰트 등등 라인꾸미기 ''' marker_cluster = folium.plugins.MarkerCluster( locations=data, popups=['lon:{}<br>lat:{}'.format(lon, lat) for (lat, lon) in data], name='EVcharger',overlay=True,control=False,icon_create_function=None) marker_cluster.add_to(m)# ''' # self.progressBar.setValue(70) m.save('temp\RoutePlanner.html')
def test_route_result(): """RouteResult should parse data into instance.""" # for routeType in ['walk', 'drive', 'cycle'] data = { "status_message": "Found route between points", "alternative_names": [["COMMONWEALTH AVENUE WEST", "NORTH BUONA VISTA ROAD"]], "route_name": ["CLEMENTI AVENUE 2", "ULU PANDAN ROAD"], "route_geometry": ("yr`oAm`k{dEksAstD~e@iW`e@{UxtAqr@pd@sVrOmItC}GZ}GJwDeSmWkm@gb@qKuEyCw" "E}AgHJiH\\kE{BaRoCoEsGcLiE{N{AmQvB{QbFkN|E}FzMcPtQmTh|A_iBfCcDzHcKpJa" "Mr\\w_@t\\i`@hb@gg@lAkJRqJg@wJeCoMgQ{f@qHsTuC_FiMsT_S_ViVkPkfAyi@oXiN" "q{@q_@qn@cU{SsGgEqAiDeAcTsGcd@eMoF{AoBi@uGkB}d@uMwDoA_EsA{QiG_VyJaSkL" "kQuN}CgDqJkKqDsFqE_H}CuE}CyEsBsGcDeKuK}f@}FiJ_FaEkKiEgHcAe~@xMsr@`LqM" "rB_En@gAy`@kBkVwE{W_^gbAkHg[aFeQaRe^_Nea@iEwYJkYsAyj@KiRkGglAcDqn@KiU" "rDkc@nFkY`Lo]lIeQfJgOfcAyhAzJ}KtPsTjIuQxFaQrBcN|E{u@rDgh@hBuYjDy_@zHo" "UbI}O|PwSkDuBiP_K{]cTq_Ack@ixAe|@_L}G{LoHynBujAsh@iZiRqK}|@ig@xg@wo@v" "{@_gA~q@g}@fUgZp^{`@gDqLv`@oNfTwH~LcIl@gEy@{PqU_V_`@cuAvHwJt^_MvXgMxC" "aD"), "route_instructions": [["10", "PANDAN LOOP", 853, 0, 89, "853m", "NE", 65, 1, "SW", 245]], "alternative_summaries": [{ "end_point": "REBECCA ROAD", "start_point": "PANDAN LOOP", "total_time": 761, "total_distance": 8133, }], "via_points": [[1.311549, 103.749657], [1.32036, 103.800156]], "route_summary": { "end_point": "REBECCA ROAD", "start_point": "PANDAN LOOP", "total_time": 740, "total_distance": 7957, }, "found_alternative": True, "status": 200, "via_indices": [0, 140], "hint_data": { "locations": [ "NzgBANtqAQBRBQAAAAAAAAQAAAAAAAAAuQIAAEOcAABoAAAAPQMUABcYLwYAAAEB", "0OUAAF4zAQChAwAABAAAAAwAAABIAAAAdQAAACx9AABoAAAAqCUUAFndLwYCAAEB", ], "checksum": 585417468, }, "alternative_geometries": [("yr`oAm`k{dEksAstD~e@iW`e@{UxtAqr@pd@sVrOmItC}GZ}GJwDeSmWkm@gb@qKu" "EyCwE}AgHJiH\\kE{BaRoCoEsGcLiE{N{AmQvB{QbFkN|E}FzMcPtQmTh|A_iBfCc" "DzHcKpJaMr\\w_@t\\i`@hb@gg@lAkJRqJg@wJeCoMgQ{f@qHsTuC_FiMsT_S_ViV" "kPkfAyi@oXiNq{@q_@qn@cU{SsGgEqAiDeAcTsGcd@eMoF{AoBi@uGkB}d@uMwDoA" "_EsA{QiG_VyJaSkLkQuN}CgDqJkKqDsFqE_H}CuE}CyEsBsGcDeKuK}f@}FiJ_FaE" "kKiEgHcAe~@xMsr@`LqMrB_En@gAy`@kBkVwE{W_^gbAkHg[aFeQaRe^_Nea@iEwY" "JkYsAyj@KiRkGglAcDqn@KiUrDkc@nFkY`Lo]lIeQfJgOfcAyhAzJ}KtPsTjIuQxF" "aQrBcN|E{u@rDgh@hBuYjDy_@zHoUbI}O|PwSkDuBiP_K{]cTq_Ack@ixAe|@_L}G" "{LoHynBujAsh@iZiRqK}|@ig@xg@wo@v{@_gA~q@g}@fUgZp^{`@gDqLv`@oNfTwH" "~LcIl@gEy@{PqU_V_`@cuAvHwJt^_MvXgMxCaD")], "alternative_instructions": [[ ["10", "PANDAN LOOP", 853, 0, 89, "853m", "NE", 65, 1, "SW", 245], ["8", "JALAN BUROH", 217, 9, 23, "217m", "NE", 50, 1, "SW", 230], [ "1", "WEST COAST HIGHWAY", 62, 14, 7, "61m", "E", 92, 1, "W", 272 ], ]], "alternative_indices": [0, 159], "debug_output": { "pathCalculationTime": 51, "pathTimes": [29, 16, 6], "precalculationTime": 87, "renderingTime": 1, "timedOut": False, "totalTime": 139, }, "elevation_metadata": { "ellipsoidToGeoidDifference": 7.473137315529, "geoidElevation": False, }, "plan": { "date": 1560468900000, "from": { "lat": 1.320981, "lon": 103.84415, "name": "Origin", "orig": "", "vertexType": "NORMAL", }, "itineraries": [{ "duration": 1023, "elevationGained": 0, "elevationLost": 0, "endTime": 1560470172000, "fare": "0.83", "legs": [{ "agencyTimeZoneOffset": 28800000, "arrivalDelay": 0, "departureDelay": 0, "distance": 441.086, "duration": 396, "endTime": 1560469545000, "from": { "departure": 1560469149000, "lat": 1.320981, "lon": 103.84415, "name": "Origin", "orig": "", "vertexType": "NORMAL", }, "interlineWithPreviousLeg": False, "intermediateStops": [], "legGeometry": { "length": 49, "points": ("i~`GsayxRCCPUMMMM@CFEHIPOBC@CA?@A\\Y@CnAmAHIBCDED" "EDCDCJGFCJCFAHAFAD?FA`@Cl@GXCXCF?TCAGC[?EB?JCPA@A" "@A?AEa@UaAAMB?"), }, "mode": "WALK", "numIntermediateStops": 1, "pathway": False, "realTime": False, "rentedBike": False, "route": "", "startTime": 1560469149000, "steps": [{ "absoluteDirection": "SOUTHEAST", "area": False, "bogusName": False, "distance": 441.086, "elevation": [], "lat": 1.3208561836374, "lon": 103.84426705983, "relativeDirection": "DEPART", "stayOn": False, "streetName": "path", }], "to": { "arrival": 1560469545000, "departure": 1560469546000, "lat": 1.31875759946, "lon": 103.846554541, "name": "REVIVAL CTR CH", "stopId": "FERRY:50111", "stopIndex": 36, "stopSequence": 38, "vertexType": "TRANSIT", }, "transitLeg": False, }], "startTime": 1560469149000, "tooSloped": False, "transfers": 0, "transitTime": 538, "waitingTime": 2, "walkDistance": 545.83289472691, "walkLimitExceeded": False, "walkTime": 483, }], "to": { "lat": 1.326762, "lon": 103.8559, "name": "Destination", "orig": "", "vertexType": "NORMAL", }, }, "request_parameters": { "arriveBy": "false", "date": "06-14-2019", "fromPlace": "1.320981,103.844150", "maxTransfers": "3", "maxWalkDistance": "1000", "mode": "TRANSIT,WALK", "numItineraries": "3", "otherThanPreferredRoutesPenalty": "0", "preferredRoutes": ("1__CC,1__DT,1__EW,1__NE,1__NS,1__PE,1__PW,1__SE,1__SS,1__SW,1__CG,1__" "BP"), "showIntermediateStops": "true", "time": "7:35am", "toPlace": "1.326762,103.8559", "transferPenalty": "7200", "waitAtBeginningFactor": "0.5", "walkReluctance": "2", }, } route_result = RouteResult(**data) attrs = [x for x in dir(route_result) if not x.startswith("__")] for attr in attrs: if attr != "lat_longs" and attr != "to_dict": assert getattr(route_result, attr) == data[attr] assert route_result.lat_longs == polyline.decode( route_result.route_geometry) route_result.route_geometry = None assert route_result.lat_longs is None
def test_decode_single_point_precision(self): d = polyline.decode('o}oolAnkcoO', 6) self.assertEqual(d, [ (40.641, -8.653) ])
def showPathAndNearbyRoutes(self, coordinate_list): # HEADER FOR EVERY MAP principal = Figure() js = JavascriptLink( QUrl.fromLocalFile( self.htmlPath.absoluteFilePath("qwebchannel.js")).toString()) principal.header.add_child(Element(js.render())) midpoint = len(coordinate_list) / 2 try: self.uk = folium.Map( #max_bounds=False, location=coordinate_list[midpoint], zoom_start=5, # min_lat=self.bbox[1], # max_lat=self.bbox[3], # min_lon=self.bbox[2], # max_lon=self.bbox[0], # max_bounds=True, tiles='StamenTerrain') except: self.uk = folium.Map( #max_bounds=False, # location=[37,-109], zoom_start=5, min_lat=self.bbox[1], max_lat=self.bbox[3], min_lon=self.bbox[2], max_lon=self.bbox[0], # max_bounds=True, tiles='StamenTerrain') self.uk.add_to(principal) fastestRoute = folium.PolyLine(coordinate_list, weight=4, color='#0095DD').add_to(self.uk) link = JavascriptLink( QUrl.fromLocalFile( self.htmlPath.absoluteFilePath("popup.js")).toString()) self.statusBar().showMessage('Getting nearby scenic routes') for route in self.true.designatedScenicRoutes.values(): # GET SCENIC ROUTES W/ CENTER IN BOUNDS OF fastestRoute ll = route['ll'] if ((float(ll[0]) > float(self.bbox[0])) and (float(ll[0]) < float(self.bbox[2])) and (float(ll[1]) > float(self.bbox[1])) and (float(ll[1]) < float(self.bbox[3]))): paths = route['path'] for path in paths: decodedPath = polyline.decode(path.strip('"')) scenicRoute = folium.PolyLine(decodedPath, weight=3, color='yellow').add_to( self.uk) f = Figure() # f.html.add_child(Element()) f.html.add_child(Element('<div id="startLat">')) f.html.add_child(Element(str(decodedPath[0][0]))) f.html.add_child(Element('</div>')) f.html.add_child(Element('<div id="startLong">')) f.html.add_child(Element(str(decodedPath[0][1]))) f.html.add_child(Element('</div>')) f.html.add_child(Element('<div id="endLat">')) f.html.add_child( Element(str(decodedPath[len(decodedPath) - 1][0]))) f.html.add_child(Element('</div>')) f.html.add_child(Element('<div id="endLong">')) f.html.add_child( Element(str(decodedPath[len(decodedPath) - 1][1]))) f.html.add_child(Element('</div>')) f.html.add_child(Element('<code id="encodedPath">')) try: f.html.add_child(Element(path)) except: lat = float(ll[1]) lon = float(ll[0]) sp = [] sp.append(lat) sp.append(lon) sillypoint = str(polyline.encode(tuple(sp))) f.html.add_child(Element(sillypoint)) f.html.add_child(Element('</code>')) f.html.add_child(Element('<div id="name">')) f.html.add_child(Element(route['name'])) f.html.add_child(Element('</div>')) f.html.add_child( Element( '<iframe id = "stv" width="285" height="220" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/streetview?key=AIzaSyDiHmblGevCJUXCkuSmeOR2l9wNErlRTw4&location=' )) #46.414382,10.013988"></iframe>')) f.html.add_child(Element(str(ll[1]).strip())) f.html.add_child(Element(',')) f.html.add_child(Element(str(ll[0]).strip())) f.html.add_child(Element('&fov=100"></iframe>')) f.html.add_child( Element('<button id="MyBtn">Add to Journey</button>')) f.html.add_child(Element(link.render())) iframe = branca.element.IFrame(html=f.render(), width=300, height=300) popup = folium.Popup(iframe, max_width=300) scenicRoute.add_child(popup) principal.save(self.htmlPath.absoluteFilePath("test.html")) self.view.load(QUrl().fromLocalFile( self.htmlPath.absoluteFilePath("test.html"))) self.statusBar().showMessage('The Means are the End') self.update() self.show()
def get_route(poly: str): route = polyline.decode(poly, 5) route = np.array(route) return route
def get_pokemarkers(): pokeMarkers = [{ 'icon': icons.dots.red, 'lat': origin_lat, 'lng': origin_lon, 'infobox': "Start position" }] for pokemon_key in pokemons: pokemon = pokemons[pokemon_key] pokemon['disappear_time_formatted'] = datetime.fromtimestamp(pokemon[ 'disappear_time']).strftime("%H:%M:%S") LABEL_TMPL = u''' <div style='position:float; top:0;left:0;'> <small> <a href='http://www.pokemon.com/us/pokedex/{id}' target='_blank' title='View in Pokedex'> #{id} </a> </small> <span> - </span> <b>{name}</b> </div> <div>disappears at {disappear_time_formatted} <span class='label-countdown' disappears-at='{disappear_time}'></span></div> ''' label = LABEL_TMPL.format(**pokemon) # NOTE: `infobox` field doesn't render multiple line string in frontend label = label.replace('\n', '') pokeMarkers.append({ 'icon': 'static/icons/%d.png' % pokemon["id"], 'lat': pokemon["lat"], 'lng': pokemon["lng"], 'infobox': label }) for gym_key in gyms: gym = gyms[gym_key] if gym[0] == 0: color = 'white' if gym[0] == 1: color = 'rgba(0, 0, 256, .1)' if gym[0] == 2: color = 'rgba(255, 0, 0, .1)' if gym[0] == 3: color = 'rgba(255, 255, 0, .1)' pokeMarkers.append({ 'icon': 'static/forts/' + numbertoteam[gym[0]] + '.png', 'lat': gym[1], 'lng': gym[2], 'infobox': "<div style='background: " + color + "'>Gym owned by Team " + numbertoteam[gym[0]], }) for stop_key in pokestops: stop = pokestops[stop_key] pokeMarkers.append({ 'icon': 'static/forts/Pstop.png', 'lat': stop[0], 'lng': stop[1], 'infobox': 'Pokestop', }) polyline = { 'stroke_color': '#0AB0DE', 'stroke_opacity': 1.0, 'stroke_weight': 3, } if len(pokeMarkers) > 1: print("get path") directions_url = 'https://maps.googleapis.com/maps/api/directions/json' params = {} # params['origin'] = 'Disneyland' params['origin'] = pokemarker_to_str(pokeMarkers[0]) params['destination'] = pokemarker_to_str(pokeMarkers[min(len(pokeMarkers) - 1, 22)]) params['waypoints'] = pokemarkers_to_str(pokeMarkers[1:min(len(pokeMarkers) - 1, 22)]) params['key'] = GOOGLEMAPS_KEY r = requests.get(directions_url, params=params, verify=False) json = r.json() if (len(json['routes']) > 0): overview_polyline = pl.decode(json['routes'][0]['overview_polyline']['points']) print(overview_polyline) optimal_path = [] for coord in overview_polyline: optimal_path.append({'lat':coord[0] ,'lng':coord[1]}) # print(len(json['routes'][0]['legs'])) polyline['path'] = optimal_path print("OPT PATH ", optimal_path) line_and_markers = {} line_and_markers["line"] = polyline line_and_markers["markers"] = pokeMarkers return line_and_markers
def get_directions(self, start_loc, target_loc, time_mode='departure', time=None): '''Returns directions object with information on how to drive from start_loc to target_loc. Parameters ---------- start_loc : str or (int,int) The starting location for directions. (location name or lat/lng tuple) target_loc : str or (int,int) The target location for directions. (location name or lat/lng tuple) time_mode : str ("departure" or "arrival") The time mode for giving directions ("departure"(default) or "arrival") time : int The time to be used for "departure" or "arrival". Given as integer seconds since midnight, January 1, 1970 UTC. Return format ------------- { 'map_bounds':{'northeast':, 'southwest':}, 'legs':[{'distance':, 'duration':, 'duration_in_traffic':, 'end_address':, 'end_location':, 'start_address':, 'start_location':, 'steps':, 'traffic_speed_entry':, 'via_waypoint':}], 'additional_info':[] } ''' #Set time to current time if not specified if time == None: #time since midnight, January 1, 1970 UTC time = int(datetime.now().replace(microsecond=0).timestamp()) directions = None if time_mode == 'departure': directions = self.gmaps.directions(start_loc, target_loc, mode='driving', departure_time=time) else: directions = self.gmaps.directions(start_loc, target_loc, mode='driving', arrival_time=time) #A little bit of formating for the result to make sense point_seq = [] for leg in directions[0]['legs']: for step in leg['steps']: point_seq = point_seq + polyline.decode( step['polyline']['points']) retobj = { 'map_bounds': directions[0]['bounds'], 'legs': directions[0]['legs'], 'polyline': polyline.encode(point_seq), 'additional_info': directions[0]['summary'] } return retobj
# colour warehouse specially info = (place.name + str(place.entry_id)).decode('utf-8') if place.entry_type == data.TYPES['warehouse']: icon_WH = folium.features.CustomIcon(logo_WH, icon_size=(50, 50)) folium.Marker(location=[place.lat, place.lon], popup=info, icon=icon_WH).add_to(route_map) # point out the last shop elif Data.make_type_id(place) == aco.BestTour[-2]: icon_end = folium.features.CustomIcon(logo_end, icon_size=(50, 50)) folium.Marker(location=[place.lat, place.lon], popup=info, icon=icon_end).add_to(route_map) else: icon_shop = folium.features.CustomIcon(logo_shop, icon_size=(40, 40)) folium.Marker(location=[place.lat, place.lon], popup=info, icon=icon_shop).add_to(route_map) color_list = ['#253494', '#2c7fb8', '#41b6c4', '#a1dab4', '#ffffcc'] for p in range(len(directions_results)): # decode all the polyline (overview_polyline) path = polyline.decode( directions_results[p][0]['overview_polyline']['points']) # map the path color = color_list[p % 5] folium.PolyLine(path, color=color, weight=5, opacity=1).add_to(route_map) route_map.save("route_map.html")
def polyline_to_points(encoded_polyline): """ decodes polyline to list of (lat, long)s """ return polyline.decode(encoded_polyline)
def get_points(self, polyline_points): crd_points = [] for points in polyline_points: crd_points += polyline.decode(points) crd_points = [x for n, x in enumerate(crd_points) if x not in crd_points[:n]] return crd_points
hike = '__________' 'Specify the mode of transportation' directions_result = gmaps.directions(startLoc, endLoc, mode="walking") #print(directions_result) 'Grabbing the time and distance of the path from the API' time = directions_result[0]['legs'][0]['duration']['text'] dist = directions_result[0]['legs'][0]['distance']['text'] print(time, dist) step = directions_result[0]['legs'][0]['steps'][0]['polyline']['points'] #print(step) steps = directions_result[0]['overview_polyline']['points'] #print(steps) stepdata = polyline.decode(str(steps)) #print(stepdata) 'Excel file must be closed in order to run the program' filePath = 'C:/Users/Austin Keller/Desktop/Hiking Dashboard/Hiking Data.xlsx' 'Open workbook' wb = pyxl.load_workbook(filePath) dataTab = wb['Trail Data'] lastRow = dataTab.max_row + 1 #stepdata = [('latitude', 'longitude'), ('latitude2', 'longitude2')] 'Write list data to cells after the last filled row in the excel column' for i in range(len(stepdata)): activeRow = lastRow + i
def euclid(s1, s2): square = pow((s1[0] - s2[0]), 2) + pow((s1[1] - s2[1]), 2) return sqrt(square) gmaps = googlemaps.Client(key='AIzaSyCciJlgQzOFXZXhvM1ORscu0Cj5dj-lTRo') # Request directions via public transit now = datetime.now() directions_result = gmaps.directions("Karlovo nám. 287/18, 120 00 Nové Město", "Karlovo nám. 319/3, 120 00 Nové Město", mode="driving", departure_time=now) location1 = [] location = '' abc = polyline.decode(directions_result[0]['overview_polyline']['points']) for i in range(0, len(abc) - 1): dis = euclid(abc[i], abc[i + 1]) if dis > maxdis: sam = dis / maxdis lat = np.linspace(abc[i][0], abc[i + 1][0], sam) lng = np.linspace(abc[i][1], abc[i + 1][1], sam) for k in range(1, len(lat) - 1): location += str(lat[k]) + ',' + str((lng[k])) + ';' location1 = str(abc[i]) location += location1.strip(')(') + '; ' print(len(location)) apiargs = { 'location': location,
str(drivers[drivername][1][1]), mode="driving", departure_time=now) else: results = gmaps.directions( str(drivers[drivername][0][0]) + "," + str(drivers[drivername][0][1]), str(drivers[drivername][1][0]) + "," + str(drivers[drivername][1][1]), mode="driving", waypoints=[waypoint], optimize_waypoints=True, departure_time=now) dbeg = getMiles( bdccGeoDistanceToPolyMtrs( polyline.decode( results[0]['overview_polyline']['points']), riders[ridername][0][0], riders[ridername][0][1])) dend = getMiles( bdccGeoDistanceToPolyMtrs( polyline.decode( results[0]['overview_polyline']['points']), riders[ridername][1][0], riders[ridername][1][1])) dis = [] if (dbeg > dend): dis.append(dend) else: dis.append(dbeg) if (dbeg > dend): dis.append(1) else: