Esempio n. 1
0
    def test_raise_over_query_limit(self):
        valid_query = ENDPOINT_DICT['directions']
        responses.add(responses.POST,
                      'https://api.openrouteservice.org/v2/directions/{}/geojson'.format(valid_query['profile']),
                      json=valid_query,
                      status=429,
                      content_type='application/json')

        with self.assertRaises(openrouteservice.exceptions._OverQueryLimit):
            client = openrouteservice.Client(key=self.key, retry_over_query_limit=False)
            client.directions(**valid_query)

        with self.assertRaises(openrouteservice.exceptions.Timeout):
            client = openrouteservice.Client(key=self.key, retry_over_query_limit=True, retry_timeout=3)
            client.directions(**valid_query)
Esempio n. 2
0
 def setUp(self):
     self.key = 'sample_key'
     self.client = openrouteservice.Client(self.key)
     self.search = {'text': 'Heidelberg',
                    'focus_point': (8.675786, 49.418431),
                    'rect_min_x': 8.573179,
                    'rect_min_y': 49.351764,
                    'rect_max_x': 8.79405,
                    'rect_max_y': 49.459693,
                    'circle_point': (8.675786, 49.418431),
                    'circle_radius': 50,
                    'sources': ['osm', 'wof', 'gn'],
                    'layers': ['locality', 'county', 'region'],
                    'country': 'de',
                    'size': 5,
                    }
     self.structured = {'address': 'Berliner Straße 45',
                        'neighbourhood': 'Neuenheimer Feld',
                        'borough': 'Heidelberg',
                        'locality': 'Heidelberg',
                        'county': 'Rhein-Neckar-Kreis',
                        'region': 'Baden-Württemberg',
                        'postalcode': '69120',
                        'country': 'de',
                        }
     self.reverse = {'point': (8.675786, 49.418431),
                     'circle_radius': 50,
                     'sources': ['osm', 'wof', 'gn'],
                     'layers': ['locality', 'county', 'region'],
                     'country': 'de',
                     'size': 5,
                     }
Esempio n. 3
0
 def __init__(self, transportation_type, **kwargs):
     """This class filters objects from the ors service.
     It gives nice methods for calling ors functions.
     """
     self.client = openrouteservice.Client(base_url=None)
     self.transportation_type = transportation_type
     super().__init__(**kwargs)
Esempio n. 4
0
def start():
    api_key = ''
    with open('route_visualization/api_key.txt', "r") as api_key_file:
        api_key = api_key_file.read()

    clnt = openrouteservice.Client(key=api_key)

    coords = read_coords_from_3_group_json()

    mapCenter = (38.945830, -92.328912)

    m = folium.Map(location=(mapCenter[0], mapCenter[1]), zoom_start=14)
    m = load_markers(m)

    global garage_matrix_g1
    garage_matrix_g1 = get_matrices(0, clnt, coords)
    global garage_matrix_g2
    garage_matrix_g2 = get_matrices(1, clnt, coords)
    global garage_matrix_g3
    garage_matrix_g3 = get_matrices(2, clnt, coords)

    optCoordsG1 = get_path(garage_matrix_g1, coords[0], 1)
    optCoordsG2 = get_path(garage_matrix_g2, coords[1], 2)
    optCoordsG3 = get_path(garage_matrix_g3, coords[2], 3)

    get_path_mapped(optCoordsG1, m, clnt, 1)
    get_path_mapped(optCoordsG2, m, clnt, 2)
    get_path_mapped(optCoordsG3, m, clnt, 3)

    save_routes(1, optCoordsG1)
    save_routes(2, optCoordsG2)
    save_routes(3, optCoordsG3)

    m.save('route_visualization/three_route_enforcement.html')
Esempio n. 5
0
 def create_route(self, coordinates):
     ors_client = ors.Client(
         key='5b3ce3597851110001cf6248f3b059537e424e639a05afc159c35d77')
     route = ors_client.directions(coordinates=coordinates,
                                   profile='driving-car',
                                   format='geojson')
     print("[create_route] " + str(coordinates))
     route_points = route['features'][0]['geometry']['coordinates']
     plt.plot(route_points[0][0], route_points[0][1], 'ro',
              markersize=16)  # Marca en punto de origen
     plt.plot(route_points[-1][0], route_points[-1][1], 'go',
              markersize=16)  # Marca en punto de destino
     route_points.append(
         route_points[-1]
     )  # Para que no haya problemas al final del siguiente for
     for p in range(
             len(route_points) -
             1):  # Linea de union entre cada par de puntos consecutivos
         col = (1, 0, 0)  # TODO cambiar el color para cada usuario
         trayectoria = mlines.Line2D(
             [route_points[p + 1][0], route_points[p][0]],
             [route_points[p + 1][1], route_points[p][1]],
             color=col,
             linewidth=4)
         plt.gca().add_line(trayectoria)
Esempio n. 6
0
def map(request, fName, kOsa):
    mapUrl = 'https://nominatim.openstreetmap.org/?addressdetails=1&q=' + fName + '+' + kOsa + '&format=json&limit=1'
    response = requests.get(mapUrl)
    data = response.json()
    lat = []
    lon = []
    if data == []:
        print("Kenttaa ei loytynyt kartalta")
        return redirect('api')
    else:
        for field in data:
            lat = field['lat']
            lon = field['lon']

    # https://openrouteservice-py.readthedocs.io/en/latest/
    myLocation = geocoder.ip('me').latlng
    coords = ((myLocation[1], myLocation[0]), (lon, lat))
    client = openrouteservice.Client(key='')  # Specify your personal API key
    routes = client.directions(coords)
    geometry = routes['routes'][0]['geometry']  #Geometriatiedot
    decoded = convert.decode_polyline(
        geometry)  #Hakee 'coordinates': [[lon, lan][lon,lan] yms...]
    route = decoded['coordinates']  #Lista koordinaateista
    for point in route:
        point.reverse()  # [lon, lat] -> [lat, lon]

    return render(
        request, 'sportFields/map.html', {
            'lat': lat,
            'lon': lon,
            'fName': fName,
            'route': route,
            'myLocation': myLocation
        })
Esempio n. 7
0
def start_ORS_client():
    import openrouteservice
    api = get_api_keys()
    ORS_api_key = api['ORS_api_key']
    ORS_client = openrouteservice.Client(
        key=ORS_api_key)  # Specify your personal API key
    return ORS_client
Esempio n. 8
0
def locate(destination):
    import openrouteservice

    #find user's current location
    startGeocoder = geocoder.ip('me')
    s_lat = startGeocoder.lat
    s_lng = startGeocoder.lng
    start_pos = (s_lng, s_lat)

    #find the coordinates of the desired location
    eg = geocoder.mapquest(destination, key=geo_key)
    e_lat = eg[0].lat
    e_lng = eg[0].lng
    end_pos = (e_lng, e_lat)

    coords = (start_pos, end_pos)
    print(coords)

    client = openrouteservice.Client(route_key)
    routes = client.directions(coords, units="mi", profile="driving-car")

    #format direction output
    output = ""
    for route in routes["routes"][0]["segments"][0]["steps"]:
        output += "In " + str(
            route["distance"]) + " miles, " + route["instruction"] + ".\n"

    return output
Esempio n. 9
0
 def __init__(
     self,
     origin: None,
     destination: None,
     api_key: str,
     travel_mode: str,
     route_mode: str,
     units: str,
     origin_reverse_geocode_enabled: bool,
     destination_reverse_geocode_enabled: bool,
 ) -> None:
     """Initialize openrouteservice."""
     self.origin = origin
     self.destination = destination
     self.travel_mode = travel_mode
     self.route_mode = route_mode
     self.attribution = None
     self.duration = None
     self.distance = None
     self.route = None
     self.base_time = None
     self.origin_name = None
     self.destination_name = None
     self.units = units
     self.origin_reverse_geocode_enabled = origin_reverse_geocode_enabled
     self.destination_reverse_geocode_enabled = destination_reverse_geocode_enabled
     self._client = openrouteservice.Client(key=api_key)
 def setUp(self):
     self.key = 'sample_key'
     self.client = openrouteservice.Client(self.key)
     self.coords_valid = [[9.970093,48.477473],
                         [9.207916,49.153868],
                         [37.573242,55.801281],
                         [115.663757,38.106467]]
def get_distance_and_duration(destination_address):

    doc = frappe.get_doc('OpenRouteService_robins_erpnext_extensions')
    client = ors.Client(key=doc.api_openrouteservice)
    home_address = doc.address_line1 + ", " + doc.pincode + " " + doc.city + ", " + doc.country

    home_address_location = client.pelias_search(text=home_address)
    home_address_coordinates = home_address_location["features"][0][
        "geometry"]["coordinates"]

    destination_address_location = client.pelias_search(
        text=destination_address)
    destination_address_coordinates = destination_address_location["features"][
        0]["geometry"]["coordinates"]

    coordinates = [home_address_coordinates, destination_address_coordinates]

    route = client.directions(coordinates=coordinates,
                              profile='driving-car',
                              geometry_simplify=True,
                              instructions=False,
                              geometry=False)

    distance_and_duration = route.get("routes")[0].get("summary")
    distance = distance_and_duration["distance"]
    duration = distance_and_duration["duration"]

    distance = distance / 1000
    duration = duration / 60

    return distance, duration
Esempio n. 12
0
    def route(self, arg1):
        self.log('I got a query:', arg1, pretty=True, lvl=debug)

        profile = 'driving-car'
        instructions = False
        simplify = True

        query = json.loads(unquote(arg1))

        self.log(query, pretty=True)

        coords = query

        client = openrouteservice.Client(key=self.key)
        routes = openrouteservice.client.directions(client,
                                                    coordinates=coords,
                                                    profile=profile,
                                                    format='geojson',
                                                    instructions=instructions,
                                                    geometry_simplify=simplify)

        self.response.headers['Content-Type'] = 'application/json'
        # self.response.headers['X-Content-Type-Options'] = 'nosniff'
        self.response.headers['Access-Control-Allow-Headers'] = '*'
        self.response.headers['Access-Control-Allow-Origin'] = '*'

        self.log(self.response.headers, pretty=True, lvl=critical)
        return json.dumps(routes)
Esempio n. 13
0
def giveDistMatrix(
        coords,
        demands,
        key='5b3ce3597851110001cf62480bea960faed84e018b953afbd3510ae7',
        dry_run=False,
        verbose=True):
    client = nav.Client(key=key)
    distanceMatrix = nav.distance_matrix.distance_matrix(
        client,
        locations=coords,
        profile='driving-car',
        sources=None,
        destinations=None,
        metrics=['distance', 'duration'],
        resolve_locations=True,
        units='m',
        optimized=True,
        validate=True,
        dry_run=dry_run)
    if (verbose):
        print(distanceMatrix)
    temp = {
        'distances': distanceMatrix['distances'],
        'durations': distanceMatrix['durations'],
        'coords': coords,
        'demands': demands
    }
    return temp
Esempio n. 14
0
def confirmSim():
    print("Inside Confirm!")
    req = eval(request.data)
    coords = ((req["source_long"], req["source_lat"]), (req["dest_long"],
                                                        req["dest_lat"]))

    client = openrouteservice.Client(
        key=api_key)  # Specify your personal API key

    # decode_polyline needs the geometry only
    while (True):
        try:
            geometry = client.directions(coords)['routes'][0]['geometry']
            break
        except Exception as e:
            print(e)
            pass
    global decoded
    decoded = convert.decode_polyline(geometry)
    decoded = decoded['coordinates']
    for i in decoded:
        i[0], i[1] = i[1], i[0]
    closest_car = get_closest_distance(req['source_lat'], req['source_long'],
                                       5)
    for i in closest_car[0]:
        i[0], i[1] = i[1], i[0]
    print(closest_car)
    global obj
    obj = car_state(closest_car[2], closest_car[0])
    return "", 200
Esempio n. 15
0
def main(file_path):
    df = FileLoader.load(file_path)
    FileLoader.display(df, 10)
    network = create_netwok(df)
    network.summary_in_file(f"{file_path}_net_summary")
    client = openrouteservice.Client(key=APIKEY)
    output = network.calc_network(client)
    network.tours[0].create_map()
    # #todo : faire un df qui fait un calcul sur le df et mettre en 2eme sheet
    output.to_excel("output.xlsx")
 def setUp(self):
     self.key = 'sample_key'
     self.client = openrouteservice.Client(self.key)
     self.query = 'Heidelberg'
     self.location = (8.68353, 49.412623)
     self.structured = {
         "postalcode": "69120",
         "country": "Germany",
         "locality": "Heidelberg",
     }
def ors_client() -> ors.Client:
    """Implement an open route service client. Needs to have a valid path to an API token text file.

    Yields:
        An open route service client.

    """
    key_path = "./ors.key"
    ors_api_key = ""
    with open(path.abspath(key_path)) as key_file:
        ors_api_key = key_file.readline().strip()

    yield ors.Client(ors_api_key)
Esempio n. 18
0
    def test_server_running(self):
        coords = ((34.482724, 31.492354), (34.492724, 31.452354))
        print("")

        feat = DistanceTimeFeature(ROAD, OSM_LINE_TABLE)
        feat.extract_coordinates(coords)

        # key can be omitted for local host
        client = openrouteservice.Client(
            base_url='http://52.236.160.138:8080/ors')

        # Only works if you didn't change the ORS endpoints manually
        routes = client.directions(coords, instructions=False, geometry=False)
        self.assertIsNotNone(routes)
 def test_overquerylimit_error(self):
     # Assume more queries_per_minute than allowed by API policy and 
     # don't allow retries if API throws 'rate exceeded' error, which 
     # should be caught.
     queries_per_minute = 110
     query_range = range(queries_per_minute * 2)
         
     client = openrouteservice.Client(key='5b3ce3597851110001cf624870cf2f2a58d44c718542b3088221b684',
                                queries_per_minute=queries_per_minute,
                                retry_over_query_limit=False)
     
     with self.assertRaises(openrouteservice.exceptions._OverQueryLimit):
         for _ in query_range:
             client.directions(self.coords_valid)
    def test_host_override_with_parameters(self):
        # Test if it's possible to override host for individual hosting.
        responses.add(responses.GET,
                      "https://foo.com/bar",
                      body='{"status":"OK","results":[]}',
                      status=200,
                      content_type="application/json")

        client = openrouteservice.Client(base_url="https://foo.com")
        client.request("/bar", {'bunny': 'pretty', 'fox': 'prettier'})

        self.assertURLEqual("https://foo.com/bar?bunny=pretty&fox=prettier",
                            responses.calls[0].request.url)
        self.assertEqual(1, len(responses.calls))
def reparse_walking_distances():
    client = openrouteservice.Client(key=openrouteservice_api_key)
    stops_df: pd.DataFrame = pd.read_pickle(FloydDataPaths.stops_df.value)
    stops_df = stops_df[['stop_name', 'stop_lon', 'stop_lat']]
    walking_distances_pickle = load_pickle(
        FloydDataPaths.api_walking_distances.value)
    api_walking_distances = walking_distances_pickle['distances']
    api_stop_list = stops_df['stop_name'].to_list()
    print(api_stop_list)

    def adjacent_stops_generator():
        for id_1, name_1, lon_1, lat_1 in stops_df.itertuples():
            for id_2, name_2, lon_2, lat_2 in stops_df.itertuples():
                if id_1 < id_2 and get_walking_distance(
                        lon_1, lat_1, lon_2, lat_2) < MAX_WALKING_DISTANCE:
                    yield name_1, lon_1, lat_1, name_2, lon_2, lat_2

    adjacent_stops = list(adjacent_stops_generator())
    all_stops = len(adjacent_stops)
    current_stop_percent = 0
    loop_counter = 0
    for name_1, lon_1, lat_1, name_2, lon_2, lat_2 in adjacent_stops:
        loop_counter += 1
        if 100 * loop_counter / all_stops >= current_stop_percent:
            print(f"{current_stop_percent}% done ")
            current_stop_percent += 1
        if (name_1, name_2) in api_walking_distances.keys():
            continue
        time.sleep(2)
        coords = ((lon_1, lat_1), (lon_2, lat_2))
        if (lon_1, lat_1) == (lon_2, lat_2):
            api_walking_distances[(name_1, name_2)] = 0
            api_walking_distances[(name_2, name_1)] = 0
        else:
            try:
                routes = directions(client, coords, profile='foot-walking')
                api_walking_distances[(
                    name_1,
                    name_2)] = routes['routes'][0]['summary']['duration']
                api_walking_distances[(
                    name_2,
                    name_1)] = routes['routes'][0]['summary']['duration']

            except openrouteservice.exceptions.ApiError:
                break
    save_pickle(
        {
            'distances': api_walking_distances,
            'stop_list': list(api_stop_list)
        }, FloydDataPaths.api_walking_distances.value)
    def test_dry_run(self):
        # Test that nothing is requested when dry_run is 'true'

        responses.add(responses.GET,
                      'https://api.openrouteservice.org/directions',
                      body='{"status":"OK","results":[]}',
                      status=200,
                      content_type='application/json')

        client = openrouteservice.Client(key=self.key)
        req = client.request(params={'format_out': 'geojson'},
                             url='directions/',
                             dry_run='true')

        self.assertEqual(0, len(responses.calls))
    def test_format_out_deprecation(self):
        bad_query = copy(self.valid_query)
        bad_query['format_out'] = "json"
        bad_query['dry_run'] = True

        self.client = openrouteservice.Client(self.key)

        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            # Trigger a warning.
            _ = self.client.directions(**bad_query)

            assert len(w) == 1
            assert issubclass(w[-1].category, DeprecationWarning)
            assert "deprecated" in str(w[-1].message)
Esempio n. 24
0
    def __init__(self, start: Point, start_bear: float, destination: Point,
                 announcer_manager: AnnouncerManager):
        # logging
        self.__logger = logging.getLogger(__name__)
        self.__logger.info("OrsRouter.__init__() called with start=" +
                           str(start) + " start_bear=" + str(start_bear) +
                           " destination=" + str(destination))

        # value initialization
        self.__start = start
        self.__start_bear = start_bear
        self.__destination = destination
        self.__announcer_manager = announcer_manager
        self.__client = openrouteservice.Client(key='key here',
                                                retry_timeout=3600)

        self.__calculate_routing_information()
Esempio n. 25
0
 def __init__(self, origin, destination, mode):
     # 設定起點終點進行路線規劃
     print("open route service directions api")
     f = open("./APIKEY", "r")
     self.key = f.read()
     self.origin = origin
     self.destination = destination
     self.mode = mode
     self.client = openrouteservice.Client(
         key=self.key)  # Specify your personal API key
     self.avoided_point_list = []
     self.idw_grid = gpd.read_file(
         './data/taipei_grid_500m_20190610052502.geojson')
     # self.barriers_level_1 = self.__selectBarriers(1)
     # self.barriers_level_2 = self.__selectBarriers(2)
     # self.barriers_level_3 = self.__selectBarriers(3)
     self.barriers = []
Esempio n. 26
0
def search():
    req = eval(request.data)
    geolocator = Nominatim()
    while (True):
        try:
            source = geolocator.geocode(req['source'])
            dest = geolocator.geocode(req['destination'])
            break
        except:
            pass

    print(source.latitude, source.longitude)
    print(dest.latitude, dest.longitude)
    i = 0
    num_cars = 0
    print("HELLO")
    while (num_cars <= 5):
        i += 0.5
        num_cars, cars = get_num_cars(source.latitude, source.longitude, i)
    print("The Number of cars is: ", num_cars)
    coords = ((source.longitude, source.latitude), (dest.longitude,
                                                    dest.latitude))

    client = openrouteservice.Client(
        key=api_key)  # Specify your personal API key

    # decode_polyline needs the geometry only
    while (True):
        try:
            geometry = client.directions(coords)['routes'][0]['geometry']
            break
        except:
            pass

    decoded = convert.decode_polyline(geometry)
    decoded = decoded['coordinates']
    for i in decoded:
        i[0], i[1] = i[1], i[0]
    return {
        "source_lat": source.latitude,
        "source_long": source.longitude,
        "dest_lat": dest.latitude,
        "dest_long": dest.longitude,
        "graph": plot_cars(source, cars, decoded)
    }
Esempio n. 27
0
def get_paths(df):

    path_list = []

    for index, row in df.iterrows():

        coords = [(row['plo'], row['pla']), (row['maplong'], row['maplat'])]
        print(coords)

        client = openrouteservice.Client(
            key='5b3ce3597851110001cf6248c196e442e9f148a9a1863fa5c168e7bc')
        geometry = client.directions(coords)['routes'][0]['geometry']
        decoded = convert.decode_polyline(geometry)
        reverse = [(y, x) for x, y in decoded['coordinates']]
        path_list.append(reverse)
        print(index)

    return path_list
    def test_raise_timeout_retriable_requests(self):
        # Mock query gives 503 as HTTP status, code should try a few times to
        # request the same and then fail on Timout() error.
        retry_timeout = 3
        responses.add(responses.GET,
                      'https://api.openrouteservice.org/directions',
                      body='{"status":"OK","results":[]}',
                      status=503,
                      content_type='application/json')

        client = openrouteservice.Client(key=self.key,
                                         retry_timeout=retry_timeout)

        start = time.time()
        with self.assertRaises(openrouteservice.exceptions.Timeout):
            client.directions(self.coords_valid)
        end = time.time()
        self.assertTrue(retry_timeout < end - start < 2 * retry_timeout)
Esempio n. 29
0
def main(coordinates):
    API_KEY = "5b3ce3597851110001cf62486d267b042a754245aeb826068a8ea035"
    client = openrouteservice.Client(key=API_KEY)
    coords = (coordinates[0], coordinates[1])
    df = pd.read_csv("points.csv")
    radiuses, points_list = extract_coordinates_radius(dataframe=df,
                                                       rad_col="radio(m)",
                                                       lng_col="Longitude",
                                                       lat_col="Latitude")
    normal_route = get_normal_route(client, coords)
    buffer_route = get_buffer_route(normal_route)
    sites_polygon = obtain_polygons(buffer_route, points_list, radiuses)
    route_detour = get_detour_route(client, coords, buffer_route,
                                    sites_polygon)
    route_coordinates = get_detour_route_coordinates(route_detour)
    route_coordinates.insert(0, list(coords[0]))
    route_coordinates.append(list(coords[1]))

    return create_route_json(route_coordinates, dtype="list")
Esempio n. 30
0
    def geocode(self, place):
        place = unquote(place)
        self.log('I got a geocode query:', place, pretty=True, lvl=debug)

        client = openrouteservice.Client(key=self.key)
        address = openrouteservice.client.pelias_autocomplete(client,
                                                              text=place)

        self.log(self.request.headers, pretty=True, lvl=verbose)
        self.response.headers['Content-Type'] = 'application/json'
        # self.response.headers['X-Content-Type-Options'] = 'nosniff'
        self.response.headers['Access-Control-Allow-Headers'] = '*'
        self.response.headers['Access-Control-Allow-Origin'] = '*'

        self.log(self.response, pretty=True, lvl=verbose)

        self.log(address, pretty=True, lvl=debug)

        return json.dumps(address)