def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) vehicle = self.request.GET.get('vehicle') if vehicle: vehicle = Vehicle.objects.get_own_vehicle_or_none( self.request.user, vehicle) route = search_route( origin=self.request.GET.get('origin'), destination=self.request.GET.get('destination'), vehicle=vehicle, ) waypoints = None if route['routes']: waypoints = decode(route['routes'][0]['sections'][0]['polyline']) # Here deep linking support a maximum of 18 waypoints indexes = sorted( random.sample(range(1, len(waypoints) - 1), min(18, len(waypoints) - 2))) waypoints = "/".join(f"{lat:.7f},{lng:.7f}" for lat, lng in waypoints[:1] + [waypoints[i] for i in indexes] + waypoints[-1:]) return { **context, 'route': json.dumps(route), 'here_key': os.getenv('HERE_JS_API_KEY'), 'waypoints': waypoints, }
def getHamiltonian(all_waypoints): ''' INPUT > List of waypoints. Example-["A","B","C"] OUTPUT> complete polyline (string) total distance (number) total duration (number) optimized sequence of waypoints ("B","A","C") ''' complete_polyline = "" total_distance = 0 total_duration = 0 all_coordinates = [] polyline_dict = gatherData(all_waypoints) all_waypoints, waypoint_distances, waypoint_durations = readData() seq = run_genetic_algorithm(all_waypoints, waypoint_distances, generations=500, population_size=20) for i in range(len(seq) - 1): complete_polyline += polyline_dict[frozenset([seq[i], seq[i + 1]])] total_distance += waypoint_distances[frozenset([seq[i], seq[i + 1]])] total_duration += waypoint_durations[frozenset([seq[i], seq[i + 1]])] all_coordinates.extend(fp.decode(complete_polyline)) #return total_distance,total_duration,seq return all_coordinates
def to_geojson(self): """Return API response as GeoJSON.""" feature_collection = FeatureCollection([]) for route in self.response["routes"]: for section in route["sections"]: polyline = section["polyline"] lstring = fp.decode(polyline) lstring = [(coord[1], coord[0], coord[2]) for coord in lstring] f = Feature(geometry=LineString(lstring), properties=section) feature_collection.features.append(f) return feature_collection
def build_routes_with_polylines(routesNodesIds, polylineMatrix): newRoutes = [] newRoute = [] for route in routesNodesIds: for i in range(len(route) - 1): newRoute.append(fp.decode(polylineMatrix[route[i]][route[i + 1]])) newRoutes.append(newRoute) newRoute = [] return (newRoutes)
def __parse_isolines_response(self, response): parsed_response = json.loads(response) isolines_response = parsed_response['isolines'] isolines = [] for isoline in isolines_response: if not isoline['polygons']: geom_value = [] else: geom_value = fp.decode(isoline['polygons'][0]['outer']) isolines.append({'range': isoline['range']['value'], 'geom': geom_value}) return isolines
def getPath(departure, arrival, maxDist, avoid=None): ## pts are (lat , lon) ## avoid : array of bbox coord (coord = [minLat, minLon, maxLat, maxLon]) ##avoid[areas]=bbox:minLong,minLat,maxLong,maxLat,bbox:..... #get a route from here API url = "https://router.hereapi.com/v8/routes?transportMode=pedestrian&origin=" + str( departure[0]) + "," + str(departure[1]) + "&destination=" + str( arrival[0]) + "," + str( arrival[1]) + "&return=polyline&apiKey=" + api_key if (avoid is not None and len(avoid) > 0): avoidQuery = "&avoid[areas]=" for i in range(0, len(avoid)): coords = avoid[i] avoidQuery = avoidQuery + "bbox:" + str(coords[1]) + "," + str( coords[0]) + "," + str(coords[3]) + "," + str(coords[2]) if (i < len(avoid) - 1): avoidQuery += "|" url += avoidQuery route = requests.get(url) print(route) path = fp.decode((route.json()["routes"][0]["sections"][0]["polyline"])) # re-sample the polyline offset = 0 pathRange = range(0, len(path) - 1) for i in pathRange: ptA = path[i + offset] ptB = path[i + 1 + offset] dist = vc(ptA, ptB) if dist > maxDist: #how many pts should we add ? nbpts = floor(dist / maxDist) #add intermediate pts for j in range(1, nbpts + 1): newPt = (ptA[0] + j * (ptB[0] - ptA[0]) / (nbpts + 1), ptA[1] + j * (ptB[1] - ptA[1]) / (nbpts + 1)) path.insert(i + j + offset, newPt) offset += nbpts return path
def getAllCoordinates(waypoint, gen_count=10): ''' INPUT > Waypoints = ['A',B','C'] gen_count = no. of generations required. Default=10 OUTPUT > [ (50.10228, 8.69821), (50.10201, 8.69567), (50.10063, 8.69150), . . . ] ''' segmentList = [(waypoint[i], waypoint[i + 1]) for i in range(len(waypoint) - 1)] getAllData(segmentList) data = getDataFromFile() population = [] all_coordinates = [] flag = False #PRODUCE GENERATIONS for i in range(gen_count): if (i == 0): population = generatePopulation(data, loop=10) popu_with_fitness = calcFitness(population, flag) fittest_routes = selectFittest(popu_with_fitness) population = crossover(fittest_routes) flag = True population = sorted(population, key=itemgetter(-1)) route = population[0] for segment in route[0:-1]: polyline = segment[1] all_coordinates.extend(fp.decode(polyline)) return all_coordinates
def decode(section): line = flexpolyline.decode(section['polyline']) line = [(coord[1], coord[0]) for coord in line] return LineString(line)
START_LNG = '78.5718' DEST_LAT = '17.2403' DEST_LNG = '78.4294' VIA_LAT = '17.4033' VIA_LNG = '78.4707' MODES = ['car', 'pedestrian', 'truck'] URL = 'https://router.hereapi.com/v8/routes?transportMode=car&origin={},{}&destination={},{}&return=polyline&apikey={}' URL = URL.format(START_LAT, START_LNG, DEST_LAT, DEST_LNG, API_KEY) URL_VIA = 'https://router.hereapi.com/v8/routes?transportMode=car&origin={},{}&destination={},{}&via={},{}&return=polyline&apikey={}' URL_VIA = URL_VIA.format(START_LAT, START_LNG, DEST_LAT, DEST_LNG, VIA_LAT, VIA_LNG, API_KEY) r = requests.get(URL) print(r.json()) polyline = r.json()["routes"][0]["sections"][0]["polyline"] coordinates_list = fp.decode(polyline) lat_list, lng_list = zip(*coordinates_list) HYD_LAT = "17.3850" HYD_LNG = "78.4867" gmap = gmplot.GoogleMapPlotter(HYD_LAT, HYD_LNG, 11) gmap.marker(float(START_LAT), float(START_LNG)) gmap.marker(float(DEST_LAT), float(DEST_LNG)) gmap.plot(lat_list, lng_list, edge_width=10) gmap.draw("my_map.html")
def _read_response(response, origin, destination, mode, fallback_extremity, request, direct_path_type): resp = response_pb2.Response() resp.status_code = 200 # routes routes = response.get('routes', []) if not routes: resp.response_type = response_pb2.NO_SOLUTION return resp route = routes[0] # sections here_sections = route.get('sections', []) if not here_sections: resp.response_type = response_pb2.NO_SOLUTION return resp here_section = here_sections[0] resp.response_type = response_pb2.ITINERARY_FOUND journey = resp.journeys.add() # durations travel_time = here_section.get('summary', {}).get('duration', 0) base_duration = here_section.get('summary', {}).get('baseDuration', 0) journey.duration = travel_time journey.durations.total = travel_time if mode == 'walking': journey.durations.walking = travel_time elif mode == 'bike': journey.durations.bike = travel_time elif mode == 'car' or mode == 'car_no_park': journey.durations.car = travel_time else: journey.durations.taxi = travel_time datetime, clockwise = fallback_extremity if (direct_path_type == StreetNetworkPathType.BEGINNING_FALLBACK or direct_path_type == StreetNetworkPathType.DIRECT): if clockwise == True: journey.departure_date_time = datetime journey.arrival_date_time = datetime + journey.duration else: journey.departure_date_time = datetime - journey.duration journey.arrival_date_time = datetime else: journey.departure_date_time = datetime - journey.duration journey.arrival_date_time = datetime journey.requested_date_time = request['datetime'] # distances length = here_section.get('summary', {}).get('length', 0) if mode == 'walking': journey.distances.walking = length elif mode == 'bike': journey.distances.bike = length elif mode == 'car' or mode == 'car_no_park': journey.distances.car = length else: journey.distances.taxi = length # co2 emission journey.co2_emission.unit = 'gEC' journey.co2_emission.value = CO2_ESTIMATION_COEFF_1 * length / 1000.0 * CO2_ESTIMATION_COEFF_2 section = journey.sections.add() section.type = response_pb2.STREET_NETWORK section.duration = travel_time section.begin_date_time = journey.departure_date_time section.end_date_time = journey.arrival_date_time # base duration impacts the base arrival and departure datetime if (direct_path_type == StreetNetworkPathType.BEGINNING_FALLBACK or direct_path_type == StreetNetworkPathType.DIRECT): section.base_begin_date_time = section.begin_date_time + ( travel_time - base_duration) section.base_end_date_time = section.end_date_time else: section.base_begin_date_time = section.begin_date_time section.base_end_date_time = section.end_date_time - ( travel_time - base_duration) section.id = 'section_0' section.length = length section.co2_emission.unit = 'gEC' section.co2_emission.value = journey.co2_emission.value section.origin.CopyFrom(origin) section.destination.CopyFrom(destination) section.street_network.length = section.length section.street_network.duration = section.duration map_mode = { fm.walking.name: response_pb2.Walking, fm.car.name: response_pb2.Car, fm.bike.name: response_pb2.Bike, fm.car_no_park.name: response_pb2.CarNoPark, } section.street_network.mode = map_mode[mode] # shape shape = fp.decode(here_section.get('polyline', '')) shape_len = len(shape) for sh in shape: coord = section.street_network.coordinates.add() coord.lon = sh[1] coord.lat = sh[0] # handle maneuvers to fill Path field def _convert_direction(direction): sentence = direction.lower() if "right" in sentence: return 90 elif "left" in sentence: return -90 else: return 0 # dynamic speed for span in here_section.get('spans', []): dynamic_speed = section.street_network.dynamic_speeds.add() dynamic_speed.geojson_offset = span.get('offset', 0) dynamic_speed_info = span.get('dynamicSpeedInfo', {}) dynamic_speed.base_speed = round( float(dynamic_speed_info.get('baseSpeed', 0)), 2) dynamic_speed.traffic_speed = round( float(dynamic_speed_info.get('trafficSpeed', 0)), 2) # instruction for idx, maneuver in enumerate(here_section.get('actions', [])): path_item = section.street_network.path_items.add() path_item.id = idx path_item.length = maneuver.get('length', 0) path_item.duration = maneuver.get('duration', 0) path_item.instruction = maneuver.get('instruction', '') path_item.name = '' path_item.direction = _convert_direction( maneuver.get('direction', '')) offset = maneuver.get('offset', 0) if offset < shape_len: path_item.instruction_start_coordinate.lat = float( shape[offset][0]) path_item.instruction_start_coordinate.lon = float( shape[offset][1]) return resp
graph = {} for index, via in enumerate(via_list): print("Calculating path via: ", via) lat, lng = via temp_url = URL_VIA.format(START_LAT, START_LNG, DEST_LAT, DEST_LNG, lat, lng, API_KEY) r = requests.get(temp_url) print("Path calculated, drawing on map...") # print(r.json()) polyline1 = r.json()["routes"][0]["sections"][0]["polyline"] polyline2 = r.json()["routes"][0]["sections"][1]["polyline"] coordinates_list1 = fp.decode(polyline1) coordinates_list2 = fp.decode(polyline2) # reducing graph size temp_list1 = [] temp_list2 = [] temp_list1.append(coordinates_list1[0]) temp_list2.append(coordinates_list2[0]) for cood in coordinates_list1: if distance(cood, temp_list1[-1]) >= 0.01: temp_list1.append(cood) for cood in coordinates_list2: if distance(cood, temp_list2[-1]) >= 0.01: temp_list2.append(cood)