def nextRoute(self, short_name, transport): self.trips.clear() if transport == "0": transport = "tram" elif transport == "3": transport = "bus" elif transport == "2": transport = "train" else: raise ValueError("Invalid transport type {} for Shaper".format(transport)) if not self.enabled: self.router = None elif short_name == "WKD": warn("Shape creation is not available for WKD line") self.router = None elif transport != self.transport: temp_xml = NamedTemporaryFile(delete=False) if transport == "train": request = requests.get(_RAIL_FILE) elif transport == "tram": request = requests.get(_TRAM_FILE) else: request = requests.get(_BUS_FILE) temp_xml.write(request.content) self.router = Router(transport, temp_xml.name) temp_xml.close() self.transport = transport
def find_route(start_lat, start_long, end_lat, end_long, transport_type='car'): ''' This function converts the lat/long distance into a meters distance. Parameters ---------- start_lat: float The start latitude start_long: float The end latitude end_lat: float The start longitude end_long: float The end longitude transport_type: string The type of transport (default is car) Returns ------- route_latlongs: arraylike array of Points representing the vertices of the route. ''' router = Router(transport_type) start = router.findNode(start_lat, start_long) end = router.findNode(end_lat, end_long) try: status, route = router.doRoute(start, end) except: return None if status == 'success': route_latlongs = list(map(router.nodeLatLon, route)) # Get actual route coordinates return route_latlongs
def Itinéraire(loc1,loc2,iti): router = Router("car") print(router) depart=router.findNode(loc1[0],loc1[1]) arrivee=router.findNode(loc2[0],loc2[1]) status, route = router.doRoute(depart, arrivee) if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) f.PolyLine(routeLatLons, color="blue", weight=7.5, opacity=8).add_to(iti)
def Itinéraire_Supérette_la_plus_proche(loc1,loc2,iti_sup): router = Router("car") print(router) depart=router.findNode(loc1[0],loc1[1]) arrivee=router.findNode(loc2[0],loc2[1]) status, route = router.doRoute(depart, arrivee) if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) f.PolyLine(routeLatLons, color="orange", weight=7.5, opacity=8).add_to(iti_sup) return iti_sup
def setWayWidth(lat, longit, mode, fileRead, width): router = Router(mode) node = router.findNode(lat, longit) #print(node) tree = ET.parse(fileRead) root = tree.getroot() findedNodeWay = ".//*[@ref='" + str(node) + "'].." data = root.findall(findedNodeWay) xmlString = "<tag k=\"width\" v=\"" + str(width) + "\"></tag>" xml = ET.fromstring(xmlString) data[0].append(xml) tree.write(fileRead) print("Done")
def locateUserRests(request,restname): customer = Customer.objects.get(email=request.session['id']) print(customer.email) restaurant =Restaurant.objects.get(name=restname) print(restaurant.name) add1=Locuser.objects.get(custid=request.session['id']) add_user=eval(add1.address_user) add2=Locrest.objects.get(restid=restaurant.email) add_rest=eval(add2.address_rest) distance=geodesic(add_user,add_rest).kilometers print(distance) router = Router("car") # Initialise it start = router.findNode(add_user[0], add_user[1]) # Find start and end nodes end = router.findNode(add_rest[0], add_rest[1]) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates latitude_list = [] longitude_list = [] for i in range(len(routeLatLons)): latitude_list.append(routeLatLons[i][0]) longitude_list.append(routeLatLons[i][1]) gmap3 = gmplot.GoogleMapPlotter(23.0, 72.53, 13) # scatter method of map object # scatter points on the google map #gmap3.scatter( latitude_list, longitude_list, '# FF0000', size = 40, marker = False ) # Plot method Draw a line in # between given coordinates gmap3.plot(latitude_list, longitude_list, 'blue', edge_width = 5) gmap3.draw( "map13.html" ) webbrowser.open_new_tab('http://127.0.0.1:8000/map13.html') return render(request,"foodspark/restview.html")
def find_route(start_lat,start_lon,end_lat,end_lon): router = Router("car") # Initialise it start = router.findNode(start_lat, start_lon) # Find start and end nodes end = router.findNode(end_lat, end_lon) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates # print(routeLatLons) Y = np.array([i[0] for i in routeLatLons]) X = np.array([i[1] for i in routeLatLons]) start_Y = Y[0] start_X = X[0] Y -= Y[0] Y *= 111392.84 Y = np.dstack((Y[:-1],Y[:-1] + np.diff(Y)/2.0)).ravel() Y = np.dstack((Y[:-1],Y[:-1] + np.diff(Y)/2.0)).ravel() Y = gaussian_filter(Y,sigma=2) X -= X[0] X *= 111392.84 X = np.dstack((X[:-1],X[:-1] + np.diff(X)/2.0)).ravel() X = np.dstack((X[:-1],X[:-1] + np.diff(X)/2.0)).ravel() X = gaussian_filter(X,sigma=2) set_track_width(10) slope = generate_slopes(X,Y) bx,by = get_bezier_track(X,Y,slope) # doing the following because working directly with GPS coordinates is not a great idea tbh. Also, these equations will only work near the equator (great for us as we live in india :P) bx /= 111392.84 by /= 111392.84 bx += start_X by += start_Y print(len(bx)) plt.scatter(bx,by) # plt.scatter(X,Y) plt.axis('equal') plt.show()
def route(mode, osm_file, in_start_end, out_json): try: print('s', time.strftime('%H:%M:%S', time.localtime(time.time()))) router = Router(mode, osm_file) # Initialise it with open(out_json, 'w') as w: f = open(in_start_end, 'r') features = loads(f.read()) x1, y1, x2, y2 = 0, 0, 0, 0 for feat in features['features']: # print(feat['geometry']['coordinates']) if feat['properties']['s_e'] == 's': x1, y1 = feat['geometry']['coordinates'] if feat['properties']['s_e'] == 'e': x2, y2 = feat['geometry']['coordinates'] start = router.findNode(y1, x1) end = router.findNode(y2, x2) status, route = router.doRoute( start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) my_feature = Feature( geometry=LineString(tuple([i[::-1] for i in routeLatLons]))) feature_collection = FeatureCollection([my_feature]) # print(feature_collection) w.write('{}'.format(dumps(feature_collection, indent=4))) print('e', time.strftime('%H:%M:%S', time.localtime(time.time()))) print('-' * 40) except Exception: pass finally: del router
def find_route(names: list, pos: (float, float), file_name: str = 'names.csv') -> dict: ''' creates a file with distance matrix among chosen places :param names: names of the places you want to visit :param pos: your position at the moment (starting point) ((yet has no use)) :param file_name: name of a file with name,lat,lon lines :return: return a dictionary {1: 'first place', 2: 'second place', ...} (for later in code) ''' places_number_name = dict() places_name_coor = dict() name_in = 'SampleIn_1.txt' name_out = 'SampleOut.txt' for i in range(len(names)): places_number_name[i + 1] = names[i] file = open(file_name, 'r') for line in file.readlines(): if line.split(sep=',')[0] in names: places_name_coor[line.split(sep=',')[0]] = (float( line.split(sep=',')[1]), float(line.split(sep=',')[2])) file.close() file_m = open(name_in, 'w', encoding='UTF-8') file_m.write(str(len(names)) + '\n') router = Router('car') for name_start in places_name_coor.keys(): start = router.findNode(places_name_coor[name_start][0], places_name_coor[name_start][1]) for name_end in places_name_coor.keys(): end = router.findNode(places_name_coor[name_end][0], places_name_coor[name_end][1]) if name_start == name_end: file_m.write('-1 ') continue status, route = router.doRoute(start, end) print(status) if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) sum_ = 0 for i in range(len(routeLatLons) - 1): sum_ += router.distance(routeLatLons[i], routeLatLons[i + 1]) file_m.write(' ' + str(sum_)[:5] + ' ') file_m.write('\n') file_m.close() return places_number_name
def _task_runner(task): (src, dt, (node_time, routing_source, routing_destination)) = task logger.debug( f"Received message at {dt} from {src} <node_time={node_time}, " f"routing_source={routing_source}, " f"routing_destination={routing_destination}>") start_timer = time.perf_counter() router = Router("car") start = router.findNode(routing_source[0], routing_source[1]) end = router.findNode(routing_destination[0], routing_destination[1]) status, route = router.doRoute(start, end) if status == "success": route_coords = [router.nodeLatLon(x) for x in route] encoded_route = (0, _format_route(route_coords)) elif status == "no_route": encoded_route = (1, None) elif status == "gave_up": encoded_route = (2, None) else: logger.error(f"Unknown result '{status}'") encoded_route = (3, None) end_timer = time.perf_counter() duration = end_timer - start_timer encoded_route_len = 0 if encoded_route[1] is None else len( encoded_route[1]) logger.debug( f"Job {task} took {duration} seconds with status {status} route length = {encoded_route_len}" ) return (src, encoded_route, duration)
class Shaper(object): def __init__(self, enabled): self.enabled = enabled self.api = overpass.API() self.router = None self.transport = None self.stops = {} self.trips = {} self.osmStops = {} self.failed = {} self.file = open("output/shapes.txt", "w", encoding="utf-8", newline="\r\n") self.file.write("shape_id,shape_pt_sequence,shape_dist_traveled,shape_pt_lat,shape_pt_lon\n") self._loadStops() def _loadStops(self): features = self.api.Get("node[public_transport=stop_position][network=\"ZTM Warszawa\"]")["features"] for i in features: try: self.osmStops[str(i["properties"]["ref"])] = i["id"] except KeyError: continue def nextRoute(self, short_name, transport): self.trips.clear() if transport == "0": transport = "tram" elif transport == "3": transport = "bus" elif transport == "2": transport = "train" else: raise ValueError("Invalid transport type {} for Shaper".format(transport)) if not self.enabled: self.router = None elif short_name == "WKD": warn("Shape creation is not available for WKD line") self.router = None elif transport != self.transport: temp_xml = NamedTemporaryFile(delete=False) if transport == "train": request = requests.get(_RAIL_FILE) elif transport == "tram": request = requests.get(_TRAM_FILE) else: request = requests.get(_BUS_FILE) temp_xml.write(request.content) self.router = Router(transport, temp_xml.name) temp_xml.close() self.transport = transport def get(self, trip_id, stops): pattern_id = trip_id.split("/")[0] + "/" + trip_id.split("/")[1] if pattern_id in self.trips: return self.trips[pattern_id] elif not self.router: return None pt_seq = 0 dist = 0.0 distances = {} for x in range(1, len(stops)): # Find nodes start_stop, end_stop = stops[x-1], stops[x] start_lat, start_lon = map(float, self.stops[start_stop]) end_lat, end_lon = map(float, self.stops[end_stop]) try: assert self.transport in ["tram", "bus"] start = self.osmStops[start_stop] assert start in self.router.data.rnodes except (AssertionError, KeyError): start = self.router.data.findNode(start_lat, start_lon) try: assert self.transport in ["tram", "bus"] end = self.osmStops[end_stop] assert end in self.router.data.rnodes except (AssertionError, KeyError): end = self.router.data.findNode(end_lat, end_lon) # Do route # SafetyCheck - start and end nodes have to be defined if start and end: try: with limit_time(10): status, route = self.router.doRoute(start, end) except Timeout: status, route = "timeout", [] route_points = list(map(self.router.nodeLatLon, route)) dist_ratio = _totalDistance(route_points) / _distance([start_lat, start_lon], [end_lat, end_lon]) # SafetyCheck - route has to have at least 2 nodes if status == "success" and len(route_points) <= 1: status = "to_few_nodes_(%d)" % len(route) # SafetyCheck - route can't be unbelivabely long than straight line between stops # Except for stops in same stop group elif stops[x-1][:4] == stops[x][:4] and dist_ratio > _OVERRIDE_RATIO.get(start_stop + "-" + end_stop, 7): status = "route_too_long_in_group_ratio:%s" % round(dist_ratio, 2) elif stops[x-1][:4] != stops[x][:4] and dist_ratio > _OVERRIDE_RATIO.get(start_stop + "-" + end_stop, 3.5): status = "route_too_long_ratio:%s" % round(dist_ratio, 2) # Apply rdp algorithm route_points = rdp(route_points, epsilon=_RDP_EPSILON) else: start, end = "n/d", "n/d" status = "no_nodes_found" if status != "success": route_points = [[start_lat, start_lon], [end_lat, end_lon]] if self.failed.get(start_stop + "-" + end_stop, True): self.failed[start_stop + "-" + end_stop] = False print("Shaper: Error between stops '%s' (%s) - '%s' (%s): %s " % (start_stop, start, end_stop, end, status)) if x == 1: # See below, except when it's the very first stop of a trip distances[1] = str(dist) self.file.write(",".join([pattern_id, str(pt_seq), str(dist), str(route_points[0][0]), str(route_points[0][1])]) + "\n") for y in range(1, len(route_points)): # Don't write the first point, as it is the same as previous stop pair last point pt_seq += 1 dist += _distance(route_points[y-1], route_points[y]) self.file.write(",".join([pattern_id, str(pt_seq), str(dist), str(route_points[y][0]), str(route_points[y][1])]) + "\n") distances[x + 1] = str(dist) self.trips[pattern_id] = distances return distances
from pyroutelib3 import Router, Datastore import pandas as pd import numpy as np import os workdir = os.getcwd() print("Loading romania-latest.osm.pbf") router = Router("car",f"{workdir}/romania-latest.osm.pbf","pbf") print('Done') #returneaza distanta si traseul dintre point1 si point2 def get_route(point1, point2): start = router.findNode(point1[0],point1[1]) end = router.findNode(point2[0],point2[1]) status, route = router.doRoute(start,end) if status == 'success': routeLatLons = list(map(router.nodeLatLon,route)) dist = 0 for crt,latlng in enumerate(routeLatLons): if crt >=1: dist = dist + Datastore.distance(routeLatLons[crt-1],routeLatLons[crt]) return([dist,routeLatLons]) else: return([]) #DISTANCE MATRIX. matrice cu distanta dintre toate punctele def get_dm(list_dm):
def post_list(request): posts = Post.objects.filter( published_date__lte=timezone.now()).order_by('published_date') ret_code = 'none' timing = '' routeLatLons = list() routeLatLonsAdd = list() #center_phi = (56.8874 + 56.8843) * 0.5 #center_lambda = (35.8652 + 35.8819) * 0.5 bound_min_phi = 56.8874 bound_max_phi = 56.8843 bound_min_la = 35.8652 bound_max_la = 35.8819 token = get_token() if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): bound_min_phi = form.cleaned_data['begin_phi'] bound_max_phi = form.cleaned_data['end_phi'] transport = form.cleaned_data['wheel_val'] ar_time_h = form.cleaned_data['arrival_time_hour'] ar_time_m = form.cleaned_data['arrival_time_minutes'] scl_time_h = form.cleaned_data['sclad_time_hour'] scl_time_m = form.cleaned_data['sclad_time_minutes'] print('before') print(ar_time_h, ar_time_m) print('scl_time_h', scl_time_h) ar_time_h, ar_time_m = add_delay(ar_time_h, ar_time_m, scl_time_h, scl_time_m) print('after') print(ar_time_h, ar_time_m) router = Router(transport) if bound_min_phi > bound_max_phi: temp = bound_min_phi bound_min_phi = bound_max_phi bound_max_phi = temp bound_min_la = form.cleaned_data['begin_lambda'] bound_max_la = form.cleaned_data['end_lambda'] if bound_min_la > bound_max_la: temp = bound_min_la bound_min_la = bound_max_la bound_max_la = temp start = router.findNode(form.cleaned_data['begin_phi'], form.cleaned_data['begin_lambda']) end = router.findNode(form.cleaned_data['end_phi'], form.cleaned_data['end_lambda']) med = router.findNode(form.cleaned_data['med_phi'], form.cleaned_data['med_lambda']) start_time = time.time() status, route = router.doRoute(start, med) sum_length = 0 time_str_1 = '' if status == 'success': # Get actual route coordinates routeLatLons = list(map(router.nodeLatLon, route)) temp_phi = 0 temp_la = 0 for point in routeLatLons: if point == routeLatLons[0]: temp_phi = point[0] temp_la = point[1] else: slat = radians(temp_phi) slon = radians(temp_la) elat = radians(point[0]) elon = radians(point[1]) dist = 6371.01 * acos( sin(slat) * sin(elat) + cos(slat) * cos(elat) * cos(slon - elon)) sum_length = sum_length + dist temp_phi = point[0] temp_la = point[1] if point[0] > bound_max_phi: bound_max_phi = point[0] if point[0] < bound_min_phi: bound_min_phi = point[0] if point[1] > bound_max_la: bound_max_la = point[1] if point[1] < bound_min_la: bound_min_la = point[1] #ret_code = 'success' #ret_code = '1-й маршрут построен, ' + 'время в пути ' + "{0:.2f}".format(sum_length / speed_list[transport]) + ' ч, ' ret_code = 'Результаты расчетов: время в пути до склада ' time_str_1 = hours_to_time_str(sum_length / speed_list[transport]) ret_code = ret_code + time_str_1 else: if ret_code == 'none': ret_code = 'Результаты расчетов: маршрут до склада отсутствует, ' else: ret_code = 'Результаты расчетов: маршрут до склада не построен, ' status, route = router.doRoute(med, end) sum_length2 = 0 time_str_2 = '' if status == 'success': # Get actual route coordinates routeLatLonsAdd = list(map(router.nodeLatLon, route)) temp_phi = 0 temp_la = 0 for point in routeLatLonsAdd: if point == routeLatLonsAdd[0]: temp_phi = point[0] temp_la = point[1] else: slat = radians(temp_phi) slon = radians(temp_la) elat = radians(point[0]) elon = radians(point[1]) dist = 6371.01 * acos( sin(slat) * sin(elat) + cos(slat) * cos(elat) * cos(slon - elon)) sum_length2 = sum_length2 + dist temp_phi = point[0] temp_la = point[1] if point[0] > bound_max_phi: bound_max_phi = point[0] if point[0] < bound_min_phi: bound_min_phi = point[0] if point[1] > bound_max_la: bound_max_la = point[1] if point[1] < bound_min_la: bound_min_la = point[1] #ret_code = 'success' ret_code = ret_code + '; время в пути до точки встречи ' time_str_2 = hours_to_time_str(sum_length2 / speed_list[transport]) ret_code = ret_code + time_str_2 else: if ret_code == 'none': ret_code = 'маршрут до точки встречи отсутствует, ' else: ret_code = 'маршрут до точки встречи не построен, ' ret_code = ret_code + '; общая длина маршрута ' + "{0:.2f}".format( sum_length + sum_length2) + ' км' ret_code = ret_code + ', время движения ' + hours_to_time_str( (sum_length + sum_length2) / speed_list[transport]) #ret_code = ret_code + ' ( ' + time_str_1 + ' до склада, ' + time_str_2 + ' до точки встречи)' ret_code = ret_code + time_to_start_str( (sum_length + sum_length2) / speed_list[transport], ar_time_h, ar_time_m) timing = 'Время выполнения расчётов: ' + "{0:.2f}".format( time.time() - start_time) + ' сек ' elif request.method == 'GET': form = NameForm() ret_code = 'Введите данные' else: form = NameForm() ret_code = 'Неправильный http-запрос' return render(request, 'blog/post_list.html', {'ret_code': ret_code, \ 'form': form, 'route': routeLatLons, 'routeAdd': routeLatLonsAdd,\ 'bound_min_phi': bound_min_phi - 0.001,\ 'bound_max_phi': bound_max_phi + 0.001, \ 'bound_min_la': bound_min_la - 0.001,\ 'bound_max_la': bound_max_la + 0.001, \ 'timing': timing, \ 'mapbox_access_token':token })
from pyroutelib3 import Router import asyncio from aiohttp import web import json from concurrent.futures import ThreadPoolExecutor # Initialise it router = Router("car", localfile="./data/ahmedabad.pbf", localfileType="pbf") loop = asyncio.get_event_loop() def caculateRoute(start, end): # Find the route - a list of OSM nodes status, route = router.doRoute(start, end) if status == 'success': return list(map(router.nodeLatLon, route)) return [] async def findRoute(request): src_lat = float(request.match_info['src_lat']) src_lng = float(request.match_info['src_lng']) dest_lat = float(request.match_info['dest_lat']) dest_lng = float(request.match_info['dest_lng']) start = router.findNode(src_lat, src_lng) end = router.findNode(dest_lat, dest_lng) with ThreadPoolExecutor() as pool:
class GetRoutInfo(object): def __init__(self, localFile): # https://wiki.openstreetmap.org/wiki/Routing pyroutelib3.TYPES["car"]['weights']['motorway'] = 20 pyroutelib3.TYPES["car"]['weights']['trunk'] = 10 pyroutelib3.TYPES["car"]['weights']['primary'] = 1 pyroutelib3.TYPES["car"]['weights']['secondary'] = 1 pyroutelib3.TYPES["car"]['weights']['tertiary'] = 1 pyroutelib3.TYPES["car"]['weights']['unclassified'] = 1 pyroutelib3.TYPES["car"]['weights']['residential'] = 0.5 pyroutelib3.TYPES["car"]['weights']['track'] = 0 pyroutelib3.TYPES["car"]['weights']['service'] = 0 if localFile: self.router = Router("car", localFile) else: self.router = Router("car") """ This methode is setting the weights for the used router Check out the follwoing web page for further details # https://wiki.openstreetmap.org/wiki/Routing """ def setRouteweights(self, motorway, trunk, primary, secondary, tertiary, unclassified, residential, track, service): pyroutelib3.TYPES["car"]['weights']['motorway'] = motorway pyroutelib3.TYPES["car"]['weights']['trunk'] = trunk pyroutelib3.TYPES["car"]['weights']['primary'] = primary pyroutelib3.TYPES["car"]['weights']['secondary'] = secondary pyroutelib3.TYPES["car"]['weights']['tertiary'] = tertiary pyroutelib3.TYPES["car"]['weights']['unclassified'] = unclassified pyroutelib3.TYPES["car"]['weights']['residential'] = residential pyroutelib3.TYPES["car"]['weights']['track'] = track pyroutelib3.TYPES["car"]['weights']['service'] = service """ This methode findes a route between two points defined by coordinates """ def routeF(self, p1Lag, p1Long, p2Lag, p2Long): self.s = (p1Lag, p1Long) self.e = (p2Lag, p2Long) start = self.router.findNode(self.s[0], self.s[1]) end = self.router.findNode(self.e[0], self.e[1]) self.filesName = "{}_{}".format(start, end) routeFile = self.filesName + "_route.json" #if file already available load it if os.path.isfile(routeFile): with open(routeFile, 'r') as f: (self.route, self.routeLatLons) = json.load(f) #self.routeLatLons = list(map(self.router.nodeLatLon, self.route)) #if no file is available calcualte route and store it else: status, self.route = self.router.doRoute(start, end) if status == 'success': self.routeLatLons = list( map(self.router.nodeLatLon, self.route)) # Get actual route coordinates with open(routeFile, 'w') as f: json.dump([self.route, self.routeLatLons], f) else: raise Exception( "could not find a route from two points p1: ({}) p2: ({}). Status:{}" .format(start, end, status)) """ This methode prints the route into a map """ def printRoute(self, dpi, width): tilemapbase.start_logging() tilemapbase.init(create=True) t = tilemapbase.tiles.build_OSM() if self.s[0] < self.e[0]: south = self.s[0] north = self.e[0] else: south = self.e[0] north = self.s[0] if self.s[1] < self.e[1]: east = self.s[1] west = self.e[1] else: east = self.e[1] west = self.s[1] degree_range = 0.1 extent = tilemapbase.Extent.from_lonlat(east - degree_range, west + degree_range, south - degree_range, north + degree_range) fig, ax = plt.subplots(figsize=(8, 8), dpi=dpi) plotter = tilemapbase.Plotter(extent, t, width=width) plotter.plot(ax, t) for i in self.routeLatLons: x, y = tilemapbase.project(i[1], i[0]) ax.scatter(x, y, marker=".", color="black", linewidth=2) plt.show() """ This methode is used to find ways onto which the nodes are placed This is done via Overpass API Due to the fact a node can be a member of several ways a simple algorithi is used which search for the correct way. """ def getWay(self): #https://www.openstreetmap.org/node/34817889 -> To see node in osm.org #http://overpass-api.de/api/interpreter?data=[out:json];node(34817889);way(bn);out; #-> what we are doing with request. wayfile = self.filesName + "_way.json" if os.path.isfile(wayfile): with open(wayfile, 'r') as f: self.way = json.load(f) else: data = [] overpass_url = "http://overpass-api.de/api/interpreter" for i in self.route: overpass_query = """ [out:json]; (node({}); way(bn); ); out center; """.format(i) while True: try: response = requests.get( overpass_url, params={'data': overpass_query}) data.append(response.json()) break except: print("error {}".format(i)) #set_trace() with open(wayfile + "temp.json", 'w') as f: json.dump(data, f) #remove not needed information elements = [] for i in range(0, len(data)): elements.append(data[i]['elements']) #filter ways a bit ways = [] for i in elements: ways.append([]) for j in i: if j['type'] == 'way': if 'tags' in j: if 'highway' in j['tags']: if j['tags']['highway'] != 'footway' \ and j['tags']['highway'] != 'raceway' \ and j['tags']['highway'] != 'bridleway' \ and j['tags']['highway'] != 'steps' \ and j['tags']['highway'] != 'path' \ and j['tags']['highway'] != 'service': ways[-1].append(j) #algorithm to detect correct way out of multible ways of singel point #initail point way = [] for i in range(0, len(ways[0])): for j in range(0, len(ways[1])): if ways[0][i]['id'] == ways[1][j]['id']: way.append(ways[0][i]) break #following points cnt = 0 for i in range(1, len(ways)): if cnt > 1: #set_trace() print("{} duplicate found".format(cnt)) for i in range(0, cnt - 1): del (way[-1]) #raise Exception("can't detect correct way point!") cnt = 0 for j in range(0, len(ways[i])): for k in range(0, len(ways[i - 1])): if ways[i][j]['id'] == ways[i - 1][k]['id']: way.append(ways[i][j]) cnt += 1 self.way = way with open(wayfile, 'w') as f: json.dump(self.way, f) """ This methode is used to extract the maxspeed data for the ways. If no maxspeed is specifired a assumption depending on the road classification is met """ def getMaxSpeed(self): speed = [] for i in self.way: if 'maxspeed' in i['tags'] and i['tags']['maxspeed'] != 'signals': speed.append(int(i['tags']['maxspeed'])) else: if i['tags']['highway'] == 'motorway': if 'tunnel' in i['tags'] and i['tags']['tunnel'] == 'yes': speed.append(100) else: speed.append(130) elif i['tags']['highway'] == 'motorway_link': speed.append(100) elif i['tags']['highway'] == 'trunk': speed.append(100) elif i['tags']['highway'] == 'trunk_link': speed.append(100) elif i['tags']['highway'] == 'primary': speed.append(100) elif i['tags']['highway'] == 'primary_link': speed.append(80) elif i['tags']['highway'] == 'secondary': speed.append(100) elif i['tags']['highway'] == 'secondary_link': speed.append(80) elif i['tags']['highway'] == 'tertiary': speed.append(70) elif i['tags']['highway'] == 'tertiary_link': speed.append(50) elif i['tags']['highway'] == 'unclassified': speed.append(70) elif i['tags']['highway'] == 'residential': speed.append(50) else: raise Exception( "can't find max speed of route:{}".format(i)) self.maxSpeed = speed """ This methode is used to create a list of distances between each node """ def getDist(self): # list of distance between nodes self.distance = [] #for i in range(0, len(self.routeLatLons) - 1): # self.distance.append(self.router.distance(self.routeLatLons[i], self.routeLatLons[i + 1])) for i in range(0, len(self.way) - 1): self.distance.append( self.router.distance([ self.way[i]['center']['lat'], self.way[i]['center']['lon'] ], [ self.way[i + 1]['center']['lat'], self.way[i + 1]['center']['lon'] ]))
import geojson from geojson import FeatureCollection, Feature, LineString, Point conn = psycopg2.connect(database='flexishuttle', user='******', password='******') curs = conn.cursor() print("Deleting previous db records.") curs.execute("DELETE FROM \"Bus\";") curs.execute("DELETE FROM \"Request\";") conn.commit() print("All records were removed\n\n") router = Router("car", "alcala.osm") def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d def route_distance(route): d = 0
def get_distance_between_two_addresses(self, first_address, second_address): # check address in db query_first = Address.select().where(Address.name == first_address) query_second = Address.select().where(Address.name == second_address) if query_first.exists() and query_second.exists(): query_distance = DistanceBetweenAddress.select().where( DistanceBetweenAddress.address_id == query_first.get().id, DistanceBetweenAddress.next_address_id == query_second.get().id) if query_distance.exists(): return query_distance.get().distance router = Router(self.calculate_method) # Initialise it coord_s_t = time.time() first_lat, first_lng = (query_first.get().lat, query_first.get().lng) if query_first.exists() else \ self.get_coordinates_from_yandex(first_address) second_lat, second_lng = (query_second.get().lat, query_second.get().lng) if query_second.exists() else \ self.get_coordinates_from_yandex(second_address) coord_e_t = time.time() start = router.findNode(first_lng, first_lat) # Find start and end nodes end = router.findNode(second_lng, second_lat) rout_s_t = time.time() status, route = router.doRoute( start, end) # Find the route - a list of OSM nodes route_e_t = time.time() if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates total_distance = 0 # calculate total distance from route coordinates for index in range(1, len(routeLatLons)): total_distance += geopy.distance.vincenty( routeLatLons[index - 1], routeLatLons[index]).km else: total_distance = 0 # это случается, когда 2 точки с одинаковым адресом, надо перепроверить print(f'{route}') first = query_first.get().id if query_first.exists( ) else Address.create(name=first_address, lat=first_lat, lng=first_lng) second = query_second.get().id if query_second.exists( ) else Address.create( name=second_address, lat=second_lat, lng=second_lng) DistanceBetweenAddress.bulk_create([ DistanceBetweenAddress(address_id=first, next_address_id=second, distance=total_distance), DistanceBetweenAddress(address_id=second, next_address_id=first, distance=total_distance) ]) print(f'COORDINATES TIME = {coord_e_t - coord_s_t} sec') print(f'ROUTE TIME = {route_e_t - rout_s_t} sec') print(total_distance, 'Total distance ==============================') return total_distance
from geopy.geocoders import Nominatim from geopy.distance import geodesic from geopy.units import miles geolocator = Nominatim(user_agent="street_address_finder_hank") from pyroutelib3 import Router # Import the router router = Router("car") # Initialise it import random def lookup_by_address(address): location = geolocator.geocode(address) return location def lookup_by_coordinates(latitude, longitude): lat_lon_string = str(latitude) + ", " + str(longitude) #location = geolocator.reverse("51.53707744842644, -0.20337486412392483") location = geolocator.reverse(lat_lon_string) return location def find_directions(start_latitude, start_longitude, end_latitude, end_longitude): start_coords = router.findNode(start_latitude, start_longitude) # Find start and end nodes end_coords = router.findNode(end_latitude, end_longitude)
from pyroutelib3 import Router import lcm from arc import req_plan_path_t, res_plan_path_t import time import sys lc = lcm.LCM() router = Router("cycle", "map.osm") def request_handler_gps(channel, data): msg = req_plan_path_t.decode(data); start = router.findNode(msg.src[0], msg.src[1]) # Find start and end nodes end = router.findNode(msg.dst[0], msg.dst[1]) print(start, end) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': rll = list(map(router.nodeLatLon, route)) res = res_plan_path_t() res.timestamp = int(time.time()*1000) res.req_timestamp = msg.timestamp res.npoints = len(rll) res.points_x = [pt[0] for pt in rll] res.points_y = [pt[1] for pt in rll] lc.publish('GPS_RES', res.encode()) print(rll) else: print (status)
from pyroutelib3 import Router, Datastore import os # print("Loading romania-latest.osm.pbf...") # workdir = os.getcwd() # router = Router("car",f"{workdir}/romania-latest.osm.pbf","pbf") # print("Loaded") router = Router("car") from sanic import Sanic from sanic.response import json, file, html, text, redirect from sanic.exceptions import abort from sanic_cors import CORS, cross_origin import async_solver import pandas as pd import numpy as np import requests import json as jjson #####SANIC APP CONFIGS##### app = Sanic(__name__, load_env=False) CORS(app, automatic_options=True, supports_credentials=True) app.config.KEEP_ALIVE = True ####ALL ERRORS##### async def server_error_handler(request, exception): return text("Error or you try too much, limit 60/minute", status=500)
def generate_route_main(ap_id, ts1, ts2, lat1, lon1, lat2, lon2, transport_mode, current_route): start_time = datetime.now() # start time ''' lat2 = 26.65317 lon2 = 128.090794 lat1 = 26.66539 lon1 = 128.103902 ''' #print ap_id,ts1, ts2, lat1,lon1, lat2, lon2, transport_mode, current_route arr_generated_rows = [] router = None if (osm_data_source != ''): router = Router(transport_mode, osm_data_source) # use local osm data else: router = Router(transport_mode) # use osm data from Internet start = None end = None try: start = router.findNode(lat1, lon1) # Find start and end nodes end = router.findNode(lat2, lon2) except: print('cannot resolve start/end OSM node:', current_route) return [] status = None route = None try: #result, route = router.doRoute(node1, node2) status, route = router.doRoute( start, end) # Find the route - a list of OSM nodes except: print('XML parse error:', current_route) return [] # ill formated osm gives errors like Unclosed Token Error is raised by the XML ETree parser, not by pyroutelib. n_points = len(route) ts_interval = (ts2 - ts1) / (n_points - 1) if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates counter = 0 for (lat, lon) in routeLatLons: ts = ts1 + ts_interval * counter #node = data.rnodes[node_id] print_line = ("%s,%f,%f,%s" % (ap_id, lat, lon, ts)) counter += 1 arr_generated_rows.insert(0, { 'ap_id': ap_id, 'timestamp': ts, 'latitude': lat, 'longitude': lon }) print("points count:", counter) else: print(("\t (%s)" % status), current_route, ' Skipping...', end="") msg = '\n %s %f,%f,%s,%f,%f,%s,--%s--' % (current_route, lat1, lon1, ts1, lat2, lon2, ts2, status) log_error(msg) #log the time and memory consumed for current transaction current_memory_mb = get_memory_usage() end_time = datetime.now() time_taken = (end_time - start_time).total_seconds() time_msg = '\n' + current_route + ',' + str( len(arr_generated_rows)) + ',' + status + ',' + str( current_memory_mb) + ',' + str(time_taken) + ',' + str( start_time) + ',' + str(end_time) #print (current_memory_mb, time_msg) log_error(msg=time_msg, log_file="log_txn_time.txt") return arr_generated_rows # number of points got
def __init__(self,Mode): self.router = Router(Mode) # Initialise it
from pyroutelib3 import Router router = Router("car", "/home/user/Desktop/maps/RU-PRI.osm") lat, lon = 45.944457, 133.805337 lat1, lon1 = 43.745925, 135.284925 start = router.data.findNode(lat, lon) # Find start and end nodes end = router.data.findNode(lat1, lon1) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates #print(status) print(route, routeLatLons, sep='\n') distance = 0 for i in range(1, len(route)): distance += router.distance(route[i - 1], route[i]) print(distance)
from pyroutelib3 import Router # Import the router router = Router("car", "map2.osm") # Initialise it archivo = open("Nodos.txt", "w") archivo2 = open("Aristas.txt", "w") ## --- MUESTRA EN CONSOLA for nodos, dic in router.data.routing.items(): print(nodos, dic) for item in dic: print(nodos, item) #print(nodos, item, dic[item]) ## --- Guarda en archivo los nodos for nodos in router.data.routing.items(): cadena = str(nodos[0]) + '\n' archivo.write(cadena) ## --- Guarda en archivo las aritas for nodos, dic in router.data.routing.items(): for item in dic: cadena2 = str(nodos) + ' ' + str(item) + '\n' archivo2.write(cadena2) #print(nodos, item) ''' ## --- ESCRIBE EN TXT for i in router.data.routing:
class RoutingUsage: def __init__(self,Mode): self.router = Router(Mode) # Initialise it def node(self,lat,longit): return [lat,longit] def getRouteMultiple(self,nodesNew): queueNodesNewRight = [] for index in range(0,len(nodesNew)-1): nodeStart = nodesNew[index] nodeEnd = nodesNew[index+1] route = self.getTheRouteBetweenTwoNodes(nodeStart[0],nodeStart[1],nodeEnd[0],nodeEnd[1]) if len(route[0]) == 0 and route[1] > 0: return None queueNodesNewRight.append(route) return queueNodesNewRight def arrangeNodesDependsOnLength(self,nodes): for nodeStartIndex in range(0,len(nodes)-1): lastDistance = self.router.distance(nodes[nodeStartIndex],nodes[nodeStartIndex+1]) for nodeNowIndex in range(nodeStartIndex+1,len(nodes)): theReturnedNodeWhichisNearst=nodes[nodeStartIndex+1] nowLength = self.router.distance(nodes[nodeStartIndex],nodes[nodeNowIndex]) #print(nowLength) theReturnedNodeIndex = nodeStartIndex if nowLength < lastDistance : theReturnedNodeWhichisNearst = nodes[nodeNowIndex] theReturnedNodeIndex = nodeNowIndex lastDistance = self.router.distance(nodes[nodeStartIndex],nodes[nodeNowIndex]) ReserveNode = nodes[nodeStartIndex+1] nodes[nodeStartIndex+1] = nodes[theReturnedNodeIndex] nodes[theReturnedNodeIndex] = ReserveNode #print("length: %f"%lastDistance) return nodes def getTheRouteBetweenTwoNodes(self,lat1,long1,lat2,long2): start = self.router.findNode(lat1,long1) # Find start and end nodes end = self.router.findNode(lat2,long2) ## print("start : %s, Lat: %s, Lon: %s "% (start,lat1,long1)) ## print("end : %s, Lat: %s, Lon: %s "% (end,lat2,long2)) status, route = self.router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(self.router.nodeLatLon, route)) # Get actual route coordinates # list the lat/long queueNodes = [] sumPath = 0 l = len(route) for index, obj in enumerate(route): thisElement = route[index] newDistance = 0 if index < l-1 : nextElement = route[index+1] thisElementD = [self.router.nodeLatLon(thisElement)[0],self.router.nodeLatLon(thisElement)[1]] nextElementD = [self.router.nodeLatLon(nextElement)[0],self.router.nodeLatLon(nextElement)[1]] newDistance = self.router.distance(nextElementD,thisElementD) sumPath = sumPath + newDistance elif index == l -1: nextElement = route[index-1] typeData = self.router.getNodeWay(thisElement,nextElement) #get width Depends on the Category width = self.router.getRouteWidth(typeData["tag"]["highway"]) #get width Depends on the way lanes numbers NumberOfLanes = typeData["tag"].get("lanes") #Const Lanes Width it will be 3 meter laneWidth = 3/12742/6*1.1 #Meter if NumberOfLanes != None: width = int(NumberOfLanes)*laneWidth #get width Depends on the way width widthUnCalibrated = typeData["tag"].get("width") if widthUnCalibrated != None: width = float(widthUnCalibrated)/12742/6*1.1 nodeNow=self.router.nodeLatLon(thisElement) nodeNext=self.router.nodeLatLon(nextElement) queueNodes.append([route[index], nodeNow[0],nodeNow[1],width]) if newDistance > 0.009: newNodesBetween = self.router.getNumberOfNodesBetweenThose(7, nodeNow,nodeNext) for nodeBet in newNodesBetween: queueNodes.append([str(index)+str(nodeBet[0])+"975", nodeBet[1],nodeBet[2],width]) #/////////////////////////////////////////////////Shift the Nodes queueNodesNewRight = [] for index, obj in enumerate(queueNodes): lV = len(queueNodes) if index < lV-1 : nextElement = [queueNodes[index+1][1],queueNodes[index+1][2]] nextElementId = queueNodes[index+1][0] thisElement = [queueNodes[index][1],queueNodes[index][2]] thisElementId = queueNodes[index][0] newDistance = self.router.distance(thisElement,nextElement) elif index == lV -1: nextElement = [queueNodes[index][1],queueNodes[index][2]] thisElement = [queueNodes[index][1],queueNodes[index][2]] newNode = self.router.getLatLongWithNewWidth(queueNodes[index][3],newDistance, thisElement,nextElement) queueNodesNewRight.append([queueNodes[index][0], newNode[0],newNode[1],queueNodes[index][3]]) return [queueNodesNewRight,sumPath] else: node1=self.node(lat1,long1) node2=self.node(lat2,long2) return [[],self.router.distance(node1,node2)]
from pyroutelib3 import Router import folium import webbrowser # creation de la carte latD, lonD=48.58626, 7.75246 # Depart : pont du Theatre latA, lonA=48.58167, 7.75048 # Arrivee : Cathedrale c = folium.Map(location = [(latA+latD)/2, (lonA+lonD)/2], zoom_start=17) #carte centree # position depart et arrivee folium.Marker((latD, lonD),popup = "Depart", icon=folium.Icon( color = 'green', icon ='home')).add_to(c) folium.Marker((latA,lonA),popup = "Arrivee", icon=folium.Icon( color = 'blue', icon = 'eye-open')).add_to(c) # itineraire "optimal" apec pyroutelib3 router = Router("foot") # cycle, foot, horse, tram, train , car depart = router.findNode(latD, lonD) arrivee = router.findNode(latA, lonA) status, route = router.doRoute(depart, arrivee) if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) folium.PolyLine(routeLatLons, color="red", weight=2.5, opacity=1).add_to(c) # sauvegarde et affichage de la carte c.save('cartev0.42.html') webbrowser.open('cartev0.42.html')
from pyroutelib3 import Router # Import the router router = Router("car") # Initialise it print("Finding") start = router.findNode(51.53495526869262, -0.20454431828209635) # Find start and end nodes end = router.findNode(51.5305246465236, -0.18548599498011692) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates print(routeLatLons)
from pyroutelib3 import Router # Import the router router = Router("car") # Initialise it start = router.data.findNode(-26.4900373, -49.0784009) # Find start and end nodes end = router.data.findNode(-26.5052854, -49.090583) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates print(routeLatLons)
from pyroutelib3 import Router # Import the router router = Router("car") # Initialise it start = router.findNode(lat=-15.80423, lon=-47.9526007) # Find start and end nodes end = router.findNode(lat=-15.8055607, lon=-47.9515105) status, route = router.doRoute(start, end) # Find the route - a list of OSM nodes print(status) print(route) if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates
def __init__(self, localFile): # https://wiki.openstreetmap.org/wiki/Routing pyroutelib3.TYPES["car"]['weights']['motorway'] = 20 pyroutelib3.TYPES["car"]['weights']['trunk'] = 10 pyroutelib3.TYPES["car"]['weights']['primary'] = 1 pyroutelib3.TYPES["car"]['weights']['secondary'] = 1 pyroutelib3.TYPES["car"]['weights']['tertiary'] = 1 pyroutelib3.TYPES["car"]['weights']['unclassified'] = 1 pyroutelib3.TYPES["car"]['weights']['residential'] = 0.5 pyroutelib3.TYPES["car"]['weights']['track'] = 0 pyroutelib3.TYPES["car"]['weights']['service'] = 0 if localFile: self.router = Router("car", localFile) else: self.router = Router("car")