Example #1
0
    def test_full_directions_alternatives(self):
        query = ENDPOINTS_QUERIES[self.name]['directions']
        coords = convert._delimit_list(
            [convert._delimit_list(pair) for pair in query['locations']], ';')

        responses.add(responses.GET,
                      'https://router.project-osrm.org/route/v1/{}/{}'.format(
                          query['profile'], coords),
                      status=200,
                      json=ENDPOINTS_RESPONSES['osrm']['directions_geojson'],
                      content_type='application/json')

        routes = self.client.directions(**query)
        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            'https://router.project-osrm.org/route/v1/car/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?'
            'alternatives=true&annotations=true&bearings=50%2C50%3B50%2C50%3B50%2C50&continue_straight=true&'
            'geometries=geojson&overview=simplified&radiuses=500%3B500%3B500&steps=true',
            responses.calls[0].request.url)
        self.assertIsInstance(routes, Directions)
        self.assertEqual(1, len(routes))
        for route in routes:
            self.assertIsInstance(route, Direction)
            self.assertIsInstance(route.duration, int)
            self.assertIsInstance(route.distance, int)
            self.assertIsInstance(route.geometry, list)
            self.assertIsInstance(route.raw, dict)
Example #2
0
    def test_directions_polyline5(self):
        query = deepcopy(ENDPOINTS_QUERIES[self.name]['directions'])
        query['geometries'] = 'polyline'
        coords = convert._delimit_list(
            [convert._delimit_list(pair) for pair in query['locations']], ';')

        responses.add(responses.GET,
                      'https://router.project-osrm.org/route/v1/{}/{}'.format(
                          query['profile'], coords),
                      status=200,
                      json=ENDPOINTS_RESPONSES['osrm']['directions_polyline'],
                      content_type='application/json')

        routes = self.client.directions(**query)
        self.assertEqual(1, len(responses.calls))
        self.assertIsInstance(routes, Directions)
        self.assertEqual(routes[0].geometry, [(49.00585, 8.4201),
                                              (49.00655, 8.42081),
                                              (49.0055, 8.42431),
                                              (49.0031, 8.424),
                                              (49.00007, 8.42706),
                                              (48.99931, 8.42977),
                                              (48.99861, 8.43061),
                                              (48.99733, 8.43029),
                                              (48.99557, 8.42693),
                                              (48.99343, 8.41368),
                                              (48.99001, 8.40377),
                                              (48.98914, 8.39766),
                                              (48.98963, 8.39105),
                                              (48.99326, 8.37727),
                                              (48.99509, 8.37446),
                                              (49.00109, 8.36855),
                                              (49.00498, 8.36562),
                                              (49.00826, 8.36039),
                                              (49.00985, 8.35546),
                                              (49.01329, 8.35302),
                                              (49.01578, 8.35314),
                                              (49.01875, 8.35509),
                                              (49.03112, 8.3599),
                                              (49.03059, 8.36915),
                                              (49.03056, 8.36984),
                                              (49.02964, 8.36965),
                                              (49.02721, 8.36776),
                                              (49.02735, 8.36538),
                                              (49.0228, 8.36605),
                                              (49.02084, 8.3655),
                                              (49.01628, 8.36188),
                                              (49.01146, 8.35694),
                                              (49.01009, 8.3583),
                                              (49.00863, 8.35403),
                                              (49.0016, 8.34494),
                                              (48.99962, 8.34374),
                                              (48.99366, 8.34198),
                                              (48.96147, 8.30189),
                                              (48.9617, 8.30051),
                                              (48.96001, 8.29851),
                                              (48.96046, 8.29766),
                                              (48.96137, 8.29873)])
Example #3
0
    def test_directions_polyline6(self):
        query = deepcopy(ENDPOINTS_QUERIES[self.name]['directions'])
        query['geometries'] = 'polyline6'
        coords = convert._delimit_list(
            [convert._delimit_list(pair) for pair in query['locations']], ';')

        responses.add(responses.GET,
                      'https://router.project-osrm.org/route/v1/{}/{}'.format(
                          query['profile'], coords),
                      status=200,
                      json=ENDPOINTS_RESPONSES['osrm']['directions_polyline6'],
                      content_type='application/json')

        routes = self.client.directions(**query)
        self.assertEqual(1, len(responses.calls))
        self.assertIsInstance(routes, Directions)
        self.assertEqual(routes[0].geometry, [(49.005852, 8.420095),
                                              (49.006554, 8.420812),
                                              (49.005502, 8.424311),
                                              (49.003102, 8.424003),
                                              (49.000065, 8.427062),
                                              (48.999306, 8.429772),
                                              (48.998613, 8.430605),
                                              (48.99733, 8.430293),
                                              (48.99557, 8.426928),
                                              (48.993431, 8.413683),
                                              (48.990011, 8.403766),
                                              (48.989135, 8.397659),
                                              (48.989626, 8.391053),
                                              (48.993257, 8.377274),
                                              (48.995086, 8.374464),
                                              (49.001092, 8.36855),
                                              (49.00498, 8.365623),
                                              (49.008261, 8.360386),
                                              (49.00985, 8.355457),
                                              (49.013291, 8.353019),
                                              (49.015775, 8.353144),
                                              (49.018752, 8.355086),
                                              (49.031121, 8.359899),
                                              (49.030589, 8.369147),
                                              (49.030558, 8.369837),
                                              (49.029636, 8.369651),
                                              (49.027214, 8.36776),
                                              (49.027346, 8.365381),
                                              (49.0228, 8.366047),
                                              (49.020841, 8.365496),
                                              (49.016277, 8.361875),
                                              (49.011464, 8.356935),
                                              (49.010093, 8.358296),
                                              (49.008632, 8.354033),
                                              (49.001596, 8.344937),
                                              (48.999617, 8.343743),
                                              (48.993659, 8.341978),
                                              (48.961471, 8.301892),
                                              (48.961703, 8.300508),
                                              (48.960006, 8.298506),
                                              (48.960459, 8.297656),
                                              (48.96137, 8.298731)])
Example #4
0
    def test_full_isochrones(self):
        query = ENDPOINTS_QUERIES[self.name]['isochrones']

        responses.add(
            responses.GET,
            'https://api.mapbox.com/isochrone/v1/{}/{}'.format(
                query["profile"],
                convert._delimit_list(query["locations"]),
            ),
            status=200,
            json=ENDPOINTS_RESPONSES[self.name]['isochrones'],
            content_type='application/json'
        )

        iso = self.client.isochrones(**query)

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            'https://api.mapbox.com/isochrone/v1/mapbox/driving/8.34234,48.23424?costing=mapbox/driving&access_token=sample_key&'
            'contours_colors=ff0000%2C00FF00&contours_minutes=10%2C20&denoise=0.1&generalize=0.5&polygons=True',
            responses.calls[0].request.url
        )
        self.assertIsInstance(iso, Isochrones)
        self.assertEqual(2, len(iso))
        for ischrone in iso:
            self.assertIsInstance(ischrone, Isochrone)
            self.assertIsInstance(ischrone.geometry, list)
            self.assertIsInstance(ischrone.interval, int)
            self.assertIsInstance(ischrone.center, list)
Example #5
0
    def test_few_sources_destinations_matrix(self):
        query = deepcopy(ENDPOINTS_QUERIES[self.name]['matrix'])
        coords = convert._delimit_list(
            [convert._delimit_list(pair) for pair in query['locations']], ';')

        query['sources'] = [1, 2]
        query['destinations'] = [0, 2]

        responses.add(responses.GET,
                      'https://router.project-osrm.org/table/v1/{}/{}'.format(
                          query['profile'], coords),
                      status=200,
                      json=ENDPOINTS_RESPONSES['osrm']['matrix'],
                      content_type='application/json')

        resp = self.client.matrix(**query)

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            'https://router.project-osrm.org/table/v1/car/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?'
            'destinations=0%3B2&sources=1%3B2', responses.calls[0].request.url)
Example #6
0
    def test_full_matrix(self):
        query = ENDPOINTS_QUERIES[self.name]['matrix']
        coords = convert._delimit_list(
            [convert._delimit_list(pair) for pair in query['locations']], ';')

        responses.add(responses.GET,
                      'https://router.project-osrm.org/table/v1/{}/{}'.format(
                          query['profile'], coords),
                      status=200,
                      json=ENDPOINTS_RESPONSES['osrm']['matrix'],
                      content_type='application/json')

        matrix = self.client.matrix(**query)

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            'https://router.project-osrm.org/table/v1/car/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776',
            responses.calls[0].request.url)
        self.assertIsInstance(matrix, Matrix)
        self.assertIsInstance(matrix.durations, list)
        self.assertIsInstance(matrix.raw, dict)
Example #7
0
    def test_few_sources_destinations_matrix(self):
        query = deepcopy(ENDPOINTS_QUERIES[self.name]['matrix'])
        coords = convert._delimit_list([convert._delimit_list(pair) for pair in query['locations']], ';')

        query['sources'] = [1, 2]
        query['destinations'] = [0, 2]

        responses.add(
            responses.GET,
            'https://api.mapbox.com/directions-matrix/v1/mapbox/{}/{}'.format(query['profile'], coords),
            status=200,
            json=ENDPOINTS_RESPONSES['mapbox_osrm']['matrix'],
            content_type='application/json'
        )

        resp = self.client.matrix(**query)

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            'https://api.mapbox.com/directions-matrix/v1/mapbox/driving/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?'
            'access_token=sample_key&annotations=distance%2Cduration&destinations=0%3B2&fallback_speed=50&sources=1%3B2',
            responses.calls[0].request.url
        )
Example #8
0
    def test_full_matrix(self):
        query = ENDPOINTS_QUERIES[self.name]['matrix']
        coords = convert._delimit_list([convert._delimit_list(pair) for pair in query['locations']], ';')

        responses.add(
            responses.GET,
            'https://api.mapbox.com/directions-matrix/v1/mapbox/{}/{}'.format(query['profile'], coords),
            status=200,
            json=ENDPOINTS_RESPONSES['mapbox_osrm']['matrix'],
            content_type='application/json'
        )

        matrix = self.client.matrix(**query)

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            'https://api.mapbox.com/directions-matrix/v1/mapbox/driving/8.688641,49.420577;8.680916,49.415776;8.780916,49.445776?'
            'access_token=sample_key&annotations=distance%2Cduration&fallback_speed=50',
            responses.calls[0].request.url
        )
        self.assertIsInstance(matrix, Matrix)
        self.assertIsInstance(matrix.distances, list)
        self.assertIsInstance(matrix.durations, list)
        self.assertIsInstance(matrix.raw, dict)
Example #9
0
        def make_waypoint(self):

            waypoint = ''
            if self.waypoint_type == 'coords':
                waypoint += convert._delimit_list(list(reversed(
                    self.position)))
            elif self.waypoint_type == 'place_id':
                waypoint += self.waypoint_type + ':' + self.position
            elif self.waypoint_type == 'enc':
                waypoint += self.waypoint_type + ':' + self.position + ':'
            else:
                raise ValueError(
                    "waypoint_type only supports enc, place_id, coords")

            if not self.stopover:
                waypoint = 'via:' + waypoint

            return waypoint
Example #10
0
    def matrix(self,
               locations,
               profile,
               sources=None,
               destinations=None,
               annotations=None,
               fallback_speed=None,
               dry_run=None):
        """
        Gets travel distance and time for a matrix of origins and destinations.

        For more information visit https://docs.mapbox.com/api/navigation/#matrix.

        :param locations: The coordinates tuple the route should be calculated
            from in order of visit.
        :type locations: list or tuple

        :param profile: Specifies the mode of transport to use when calculating
            directions. One of ["car", "bike", "foot"].
        :type profile: str

        :param sources: A list of indices that refer to the list of locations
            (starting with 0). If not passed, all indices are considered.
        :type sources: list or tuple

        :param destinations: A list of indices that refer to the list of locations
            (starting with 0). If not passed, all indices are considered.
        :type destinations: list or tuple

        :param annotations: Used to specify the resulting matrices. One or more of ["duration", "distance"]. Default
            ["duration"]
        :type annotations: list of str

        :param fallback_speed: 	By default, if there is no possible route between two points, the Matrix API sets the
            resulting matrix element to null. To circumvent this behavior, set the fallback_speed parameter to a
            value greater than 0 in kilometers per hour. The Matrix API will replace a null value with a straight-line
            estimate between the source and destination based on the provided speed value.
        :type fallback_speed: int

        :param dry_run: Print URL and parameters without sending the request.
        :param dry_run: bool

        :returns: A matrix from the specified sources and destinations.
        :rtype: :class:`routingpy.matrix.Matrix`
        """

        coords = convert._delimit_list([
            convert._delimit_list([convert._format_float(f) for f in pair])
            for pair in locations
        ], ';')

        params = {'access_token': self.api_key}

        if sources:
            params['sources'] = convert._delimit_list(sources, ';')

        if destinations:
            params['destinations'] = convert._delimit_list(destinations, ';')

        if annotations:
            params['annotations'] = convert._delimit_list(annotations)

        if fallback_speed:
            params['fallback_speed'] = str(fallback_speed)

        return self._parse_matrix_json(
            self._request("/directions-matrix/v1/mapbox/" + profile + '/' +
                          coords,
                          get_params=params,
                          dry_run=dry_run))
Example #11
0
    def isochrones(self,
                   locations,
                   profile,
                   intervals,
                   contours_colors=None,
                   polygons=None,
                   denoise=None,
                   generalize=None,
                   dry_run=None):
        """Gets isochrones or equidistants for a range of time values around a given set of coordinates.

        For more information, visit https://github.com/valhalla/valhalla/blob/master/docs/api/isochrone/api-reference.md.

        :param locations: One pair of lng/lat values. Takes the form [Longitude, Latitude].
        :type locations: list of float

        :param profile: Specifies the mode of transport to use when calculating
            directions. One of ["mapbox/driving", "mapbox/walking", "mapbox/cycling".
        :type profile: str

        :param intervals: Time ranges to calculate isochrones for. Up to 4 ranges are possible. In seconds.
        :type intervals: list of int

        :param contours_colors: The color for the output of the contour. Specify it as a Hex value, but without the #, such as
            "color":"ff0000" for red. If no color is specified, the isochrone service will assign a default color to the output.
        :type contours_colors: list of str

        :param polygons: Controls whether polygons or linestrings are returned in GeoJSON geometry. Default False.
        :type polygons: bool

        :param denoise: Can be used to remove smaller contours. In range [0, 1]. A value of 1 will only return the largest contour
            for a given time value. A value of 0.5 drops any contours that are less than half the area of the largest
            contour in the set of contours for that same time value. Default 1.
        :type denoise: float

        :param generalize: A floating point value in meters used as the tolerance for Douglas-Peucker generalization.
            Note: Generalization of contours can lead to self-intersections, as well as intersections of adjacent contours.
        :type generalize: float

        :param dry_run: Print URL and parameters without sending the request.
        :param dry_run: bool

        :returns: An isochrone with the specified range.
        :rtype: :class:`routingpy.isochrone.Isochrones`
        """

        params = {
            "contours_minutes":
            convert._delimit_list([int(x / 60) for x in sorted(intervals)],
                                  ','),
            'access_token':
            self.api_key,
            'costing':
            profile
        }

        locations_string = convert._delimit_list(locations, ',')

        if contours_colors:
            params["contours_colors"] = convert._delimit_list(
                contours_colors, ',')

        if polygons is not None:
            params['polygons'] = polygons

        if denoise:
            params['denoise'] = denoise

        if generalize:
            params['generalize'] = generalize

        return self._parse_isochrone_json(
            self._request("/isochrone/v1/" + profile + '/' + locations_string,
                          get_params=params,
                          dry_run=dry_run), intervals, locations)
Example #12
0
    def directions(self,
                   locations,
                   profile,
                   radiuses=None,
                   bearings=None,
                   alternatives=None,
                   steps=None,
                   continue_straight=None,
                   annotations=None,
                   geometries=None,
                   overview=None,
                   dry_run=None):
        """Get directions between an origin point and a destination point.

        For more information, visit http://project-osrm.org/docs/v5.5.1/api/#route-service.

        :param locations: The coordinates tuple the route should be calculated
            from in order of visit.
        :type locations: list of list

        :param profile: Specifies the mode of transport to use when calculating
            directions. One of ["car", "bike", "foot"].
        :type profile: str

        :param radiuses: A list of maximum distances (measured in
            meters) that limit the search of nearby road segments to every given waypoint.
            The values must be greater than 0, an empty element signifies to use the backend default
            radius. The number of radiuses must correspond to the number of waypoints.
        :type radiuses: list of int

        :param bearings: Specifies a list of pairs (bearings and
            deviations) to filter the segments of the road network a waypoint can
            snap to. For example bearings=[[45,10],[120,20]]. Each pair is a
            comma-separated list that can consist of one or two float values, where
            the first value is the bearing and the second one is the allowed deviation
            from the bearing. The bearing can take values between 0 and 360 clockwise
            from true north. If the deviation is not set, then the default value of
            100 degrees is used. The number of pairs must correspond to the number
            of waypoints.
        :type bearings: list of list

        :param alternatives: Search for alternative routes. A result cannot be guaranteed. Accepts an integer or False.
            Default False.
        :type alternatives: bool or int

        :param steps: Return route steps for each route leg. Default false.
        :type steps: bool

        :param continue_straight: Forces the route to keep going straight at waypoints constraining
            uturns there even if it would be faster. Default value depends on the profile.
        :type continue_straight: bool

        :param annotations: Returns additional metadata for each coordinate along the route geometry. Default false.
        :type annotations: bool

        :param geometries: Returned route geometry format (influences overview and per step). One of ["polyline",
            "polyline6", "geojson". Default polyline.
        :type geometries: str

        :param overview: Add overview geometry either full, simplified according to highest zoom level
            it could be display on, or not at all. One of ["simplified", "full", "false", False]. Default simplified.
        :type overview: str

        :param dry_run: Print URL and parameters without sending the request.
        :param dry_run: bool

        :returns: One or multiple route(s) from provided coordinates and restrictions.
        :rtype: :class:`routingpy.direction.Direction` or :class:`routingpy.direction.Directions`
        """

        coords = convert._delimit_list([
            convert._delimit_list([convert._format_float(f) for f in pair])
            for pair in locations
        ], ';')

        params = dict()

        if radiuses:
            params["radiuses"] = convert._delimit_list(radiuses, ';')

        if bearings:
            params["bearings"] = convert._delimit_list(
                [convert._delimit_list(pair) for pair in bearings], ';')

        if alternatives is not None:
            params["alternatives"] = convert._convert_bool(alternatives)

        if steps is not None:
            params["steps"] = convert._convert_bool(steps)

        if continue_straight is not None:
            params["continue_straight"] = convert._convert_bool(
                continue_straight)

        if annotations is not None:
            params["annotations"] = convert._convert_bool(annotations)

        if geometries:
            params["geometries"] = geometries

        if overview is not None:
            params["overview"] = convert._convert_bool(overview)

        return self._parse_direction_json(
            self._request("/route/v1/" + profile + '/' + coords,
                          get_params=params,
                          dry_run=dry_run), alternatives, geometries)
Example #13
0
    def matrix(self,
               locations,
               profile,
               radiuses=None,
               bearings=None,
               sources=None,
               destinations=None,
               dry_run=None,
               annotations=['duration', 'distance']):
        """
        Gets travel distance and time for a matrix of origins and destinations.

        For more information visit http://project-osrm.org/docs/v5.5.1/api/#table-service.

        :param locations: The coordinates tuple the route should be calculated
            from.
        :type locations: list of list

        :param profile: Specifies the mode of transport to use when calculating
            directions. One of ["car", "bike", "foot"].
        :type profile: str

        :param radiuses: A list of maximum distances (measured in
            meters) that limit the search of nearby road segments to every given waypoint.
            The values must be greater than 0, an empty element signifies to use the backend default
            radius. The number of radiuses must correspond to the number of waypoints.
        :type radiuses: list of int

        :param bearings: Specifies a list of pairs (bearings and
            deviations) to filter the segments of the road network a waypoint can
            snap to. For example bearings=[[45,10],[120,20]]. Each pair is a
            comma-separated list that can consist of one or two float values, where
            the first value is the bearing and the second one is the allowed deviation
            from the bearing. The bearing can take values between 0 and 360 clockwise
            from true north. If the deviation is not set, then the default value of
            100 degrees is used. The number of pairs must correspond to the number
            of waypoints.
        :type bearings: list of list

        :param sources: A list of indices that refer to the list of locations
            (starting with 0). If not passed, all indices are considered.
        :type sources: list of int

        :param destinations: A list of indices that refer to the list of locations
            (starting with 0). If not passed, all indices are considered.
        :type destinations: list of int

        :param dry_run: Print URL and parameters without sending the request.
        :type dry_run: bool

        :param annotations: Return the requested table or tables in response.
            One or more of ["duration", "distance"].
        :type annotations: List[str]

        :returns: A matrix from the specified sources and destinations.
        :rtype: :class:`routingpy.matrix.Matrix`

        .. versionchanged:: 0.3.0
           Add annotations parameter to get both distance and duration
        """

        coords = convert._delimit_list([
            convert._delimit_list([convert._format_float(f) for f in pair])
            for pair in locations
        ], ';')

        params = dict()

        if sources:
            params['sources'] = convert._delimit_list(sources, ';')

        if destinations:
            params['destinations'] = convert._delimit_list(destinations, ';')

        if annotations:
            params['annotations'] = convert._delimit_list(annotations)

        return self._parse_matrix_json(
            self._request("/table/v1/" + profile + '/' + coords,
                          get_params=params,
                          dry_run=dry_run))
Example #14
0
    def matrix(self,
               locations,
               profile,
               sources=None,
               destinations=None,
               avoid=None,
               language=None,
               region=None,
               units=None,
               arrival_time=None,
               departure_time=None,
               traffic_model=None,
               transit_mode=None,
               transit_routing_preference=None,
               dry_run=None):
        """ Gets travel distance and time for a matrix of origins and destinations.

        :param locations: Two or more pairs of lng/lat values.
        :type locations: list of list

        :param profile: The vehicle for which the route should be calculated.
            Default "driving". One of ['driving', 'walking', 'bicycling', 'transit'].
        :type profile: str

        :param sources: A list of indices that refer to the list of locations
            (starting with 0). If not passed, all indices are considered.
        :type sources: list or tuple

        :param destinations: A list of indices that refer to the list of locations
            (starting with 0). If not passed, all indices are considered.
        :type destinations: list or tuple

        :param avoid: Indicates that the calculated route(s) should avoid the indicated features. One or more of
            ['tolls', 'highways', 'ferries', 'indoor']. Default None.
        :param avoid: list of str

        :param language: Language for routing instructions. The locale of the resulting turn instructions. Visit
            https://developers.google.com/maps/faq#languagesupport for options.
        :type language: str

        :param region: Specifies the region code, specified as a ccTLD ("top-level domain") two-character value.
            See https://developers.google.com/maps/documentation/directions/intro#RegionBiasing.
        :type region: str

        :param units: Specifies the unit system to use when displaying results. One of ['metric', 'imperial'].
        :type units: str

        :param arrival_time: Specifies the desired time of arrival for transit directions, in seconds since midnight,
            January 1, 1970 UTC. Incompatible with departure_time.
        :type arrival_time: int

        :param departure_time: Specifies the desired time of departure. You can specify the time as an integer in
            seconds since midnight, January 1, 1970 UTC.
        :type departure_time: int

        :param traffic_model: Specifies the assumptions to use when calculating time in traffic. One of ['best_guess',
            'pessimistic', 'optimistic'. See https://developers.google.com/maps/documentation/directions/intro#optional-parameters
            for details.
        :type traffic_model: str

        :param transit_mode: Specifies one or more preferred modes of transit. One or more of ['bus', 'subway', 'train',
            'tram', 'rail'].
        :type transit_mode: list of str or tuple of str

        :param transit_routing_preference: Specifies preferences for transit routes. Using this parameter, you can bias
            the options returned, rather than accepting the default best route chosen by the API. One of ['less_walking',
            'fewer_transfers'].
        :type transit_routing_preference: str

        :param dry_run: Print URL and parameters without sending the request.
        :param dry_run: bool

        :returns: A matrix from the specified sources and destinations.
        :rtype: :class:`routingpy.matrix.Matrix`
        """
        params = {'mode': profile}

        waypoints = []
        for coord in locations:
            if isinstance(coord, (list, tuple)):
                waypoints.append(convert._delimit_list(list(reversed(coord))))
            elif isinstance(coord, self.WayPoint):
                waypoints.append(coord.make_waypoint())

        sources_coords = waypoints
        if sources is not None:
            sources_coords = itemgetter(*sources)(sources_coords)
            if not isinstance(sources_coords, (list, tuple)):
                sources_coords = [sources_coords]
        params['origins'] = convert._delimit_list(sources_coords, '|')

        destinations_coords = waypoints
        if destinations is not None:
            destinations_coords = itemgetter(
                *destinations)(destinations_coords)
            if not isinstance(destinations_coords, (list, tuple)):
                destinations_coords = [destinations_coords]
        params['destinations'] = convert._delimit_list(destinations_coords,
                                                       '|')

        if self.key is not None:
            params["key"] = self.key

        if avoid:
            params['avoid'] = convert._delimit_list(avoid, '|')

        if language:
            params['language'] = language

        if region:
            params['region'] = region

        if units:
            params['units'] = units

        if arrival_time:
            params['arrival_time'] = str(arrival_time)

        if departure_time:
            params['departure_time'] = str(departure_time)

        if traffic_model:
            params['traffic_model'] = traffic_model

        if transit_mode:
            params['transit_mode'] = convert._delimit_list(transit_mode, '|')

        if transit_routing_preference:
            params['transit_routing_preference'] = transit_routing_preference

        return self._parse_matrix_json(
            self._request('/distancematrix/json',
                          get_params=params,
                          dry_run=dry_run))
Example #15
0
    def directions(self,
                   locations,
                   profile,
                   alternatives=None,
                   avoid=None,
                   optimize=None,
                   language=None,
                   region=None,
                   units=None,
                   arrival_time=None,
                   departure_time=None,
                   traffic_model=None,
                   transit_mode=None,
                   transit_routing_preference=None,
                   dry_run=None):
        """Get directions between an origin point and a destination point.

        For more information, visit https://developers.google.com/maps/documentation/directions/intro.

        :param locations: The coordinates tuple the route should be calculated
            from in order of visit. Can be a list/tuple of [lon, lat], a list/tuple of address strings, Google's
            Place ID's, a :class:`Google.WayPoint` instance or a combination of these. Note, the first and last location have to be specified as [lon, lat].
            Optionally, specify ``optimize=true`` for via waypoint optimization.
        :type locations: list of list or list of :class:`Google.WayPoint`

        :param profile: The vehicle for which the route should be calculated.
            Default "driving". One of ['driving', 'walking', 'bicycling', 'transit'].
        :type profile: str

        :param alternatives: Specifies whether more than one route should be returned.
            Only available for requests without intermediate waypoints. Default False.
        :type alternatives: bool

        :param avoid: Indicates that the calculated route(s) should avoid the indicated features. One or more of
            ['tolls', 'highways', 'ferries', 'indoor']. Default None.
        :param avoid: list of str

        :param optimize: Optimize the given order of via waypoints (i.e. between first and last location). Default False.
        :type optimize: bool

        :param language: Language for routing instructions. The locale of the resulting turn instructions. Visit
            https://developers.google.com/maps/faq#languagesupport for options.
        :type language: str

        :param region: Specifies the region code, specified as a ccTLD ("top-level domain") two-character value.
            See https://developers.google.com/maps/documentation/directions/intro#RegionBiasing.
        :type region: str

        :param units: Specifies the unit system to use when displaying results. One of ['metric', 'imperial'].
        :type units: str

        :param arrival_time: Specifies the desired time of arrival for transit directions, in seconds since midnight,
            January 1, 1970 UTC. Incompatible with departure_time.
        :type arrival_time: int

        :param departure_time: Specifies the desired time of departure. You can specify the time as an integer in
            seconds since midnight, January 1, 1970 UTC.

        :param traffic_model: Specifies the assumptions to use when calculating time in traffic. One of ['best_guess',
            'pessimistic', 'optimistic'. See https://developers.google.com/maps/documentation/directions/intro#optional-parameters
            for details.
        :type traffic_model: str

        :param transit_mode: Specifies one or more preferred modes of transit. One or more of ['bus', 'subway', 'train',
            'tram', 'rail'].
        :type transit_mode: list/tuple of str

        :param transit_routing_preference: Specifies preferences for transit routes. Using this parameter, you can bias
            the options returned, rather than accepting the default best route chosen by the API. One of ['less_walking',
            'fewer_transfers'].
        :type transit_routing_preference: str

        :param dry_run: Print URL and parameters without sending the request.
        :param dry_run: bool

        :returns: One or multiple route(s) from provided coordinates and restrictions.
        :rtype: :class:`routingpy.direction.Direction` or :class:`routingpy.direction.Directions`
        """

        params = {'mode': profile}

        origin, destination = locations[0], locations[-1]
        if isinstance(origin, (list, tuple)):
            params['origin'] = convert._delimit_list(list(reversed(origin)))
        elif isinstance(origin, self.WayPoint):
            raise TypeError(
                "The first and last locations must be list/tuple of [lon, lat]"
            )

        if isinstance(destination, (list, tuple)):
            params['destination'] = convert._delimit_list(
                list(reversed(destination)))
        elif isinstance(origin, self.WayPoint):
            raise TypeError(
                "The first and last locations must be list/tuple of [lon, lat]"
            )

        if len(locations) > 2:
            waypoints = []
            s = slice(1, -1)
            for coord in locations[s]:
                if isinstance(coord, (list, tuple)):
                    waypoints.append(
                        convert._delimit_list(list(reversed(coord))))
                elif isinstance(coord, self.WayPoint):
                    waypoints.append(coord.make_waypoint())
            if optimize:
                waypoints.insert(0, 'optimize:true')

            params['waypoints'] = convert._delimit_list(waypoints, '|')

        if self.key is not None:
            params["key"] = self.key

        if alternatives is not None:
            params['alternatives'] = convert._convert_bool(alternatives)

        if avoid:
            params['avoid'] = convert._delimit_list(avoid, '|')

        if language:
            params['language'] = language

        if region:
            params['region'] = region

        if units:
            params['units'] = units

        if arrival_time and departure_time:
            raise ValueError("Specify either arrival_time or departure_time.")

        if arrival_time:
            params['arrival_time'] = str(arrival_time)

        if departure_time:
            params['departure_time'] = str(departure_time)

        if traffic_model:
            params['traffic_model'] = traffic_model

        if transit_mode:
            params['transit_mode'] = convert._delimit_list(transit_mode, '|')

        if transit_routing_preference:
            params['transit_routing_preference'] = transit_routing_preference

        return self._parse_direction_json(
            self._request('/directions/json',
                          get_params=params,
                          dry_run=dry_run), alternatives)
Example #16
0
    def test_delimit_list_error(self):

        falses = ['8', 8, {'a': 'b', 3: 'a', 4: 4}]
        for f in falses:
            with self.assertRaises(TypeError):
                convert._delimit_list(f)
Example #17
0
    def directions(self,
                   locations,
                   profile,
                   radiuses=None,
                   bearings=None,
                   alternatives=None,
                   steps=None,
                   continue_straight=None,
                   annotations=None,
                   geometries=None,
                   overview=None,
                   exclude=None,
                   approaches=None,
                   banner_instructions=None,
                   language=None,
                   roundabout_exits=None,
                   voice_instructions=None,
                   voice_units=None,
                   waypoint_names=None,
                   waypoint_targets=None,
                   dry_run=None):
        """Get directions between an origin point and a destination point.

        For more information, visit https://docs.mapbox.com/api/navigation/#directions.

        :param locations: The coordinates tuple the route should be calculated
            from in order of visit.
        :type locations: list of list

        :param profile: Specifies the mode of transport to use when calculating
            directions. One of ["driving-traffic", "driving", "walking", "cycling"].
        :type profile: str

        :param radiuses: A list of maximum distances (measured in
            meters) that limit the search of nearby road segments to every given waypoint.
            The values must be greater than 0, an empty element signifies to use the backend default
            radius. The number of radiuses must correspond to the number of waypoints.
        :type radiuses: list or tuple

        :param bearings: Specifies a list of pairs (bearings and
            deviations) to filter the segments of the road network a waypoint can
            snap to. For example bearings=[[45,10],[120,20]]. Each pair is a
            comma-separated list that can consist of one or two float values, where
            the first value is the bearing and the second one is the allowed deviation
            from the bearing. The bearing can take values between 0 and 360 clockwise
            from true north. If the deviation is not set, then the default value of
            100 degrees is used. The number of pairs must correspond to the number
            of waypoints.
        :type bearings: list of list of int

        :param alternatives: Search for alternative routes and return as well. A result cannot be guaranteed.
            Default false.
        :type alternatives: bool

        :param steps: Return route steps for each route leg. Default false.
        :type steps: bool

        :param continue_straight: Forces the route to keep going straight at waypoints constraining
            uturns there even if it would be faster. Default value depends on the profile.
        :type continue_straight: bool

        :param annotations: Returns additional metadata for each coordinate along the route geometry.
            One of [duration, distance, speed, congestion].
        :type annotations: list of str

        :param geometries: Returned route geometry format (influences overview and per step). One of ["polyline",
            "polyline6", "geojson". Default polyline.
        :type geometries: str

        :param overview: Add overview geometry either full, simplified according to highest zoom level
            it could be display on, or not at all. One of ["simplified", "full", "false", False]. Default simplified.
        :type overview: str

        :param exclude: Exclude certain road types from routing. One of ['toll', 'motorway', 'ferry'] if profile=driving*.
            'ferry' for profile=cycling. None for profile=walking. Default none.
        :type exclude: str

        :param approaches: Indicating the side of the road from which to approach waypoint
            in a requested route. One of ["unrestricted", "curb"]. unrestricted: route can arrive at the waypoint from
            either side of the road. curb: route will arrive at the waypoint on the driving_side of the region. If provided,
            the number of approaches must be the same as the number of waypoints.
            Default unrestricted.
        :type approaches: list of str

        :param banner_instructions: Whether to return banner objects associated with the route steps. Default False.
        :type banner_instructions: bool

        :param language: The language of returned turn-by-turn text instructions. Default is en.
            See the full list here of supported languages here:
            https://docs.mapbox.com/api/navigation/#instructions-languages
        :type language: str

        :param roundabout_exits: Whether to emit instructions at roundabout exits or not.
            Without this parameter, roundabout maneuvers are given as a single instruction that includes both entering
            and exiting the roundabout. With roundabout_exits=true, this maneuver becomes two instructions, one for
            entering the roundabout and one for exiting it. Default false.
        :type roundabout_exits: bool

        :param voice_instructions: Whether to return SSML marked-up text for voice guidance along the route or not.
            Default false.
        :type voice_instructions: bool

        :param voice_units: Specify which type of units to return in the text for voice instructions. One of
            ["imperial", "metric"]. Default imperial.
        :type voice_units: str

        :param waypoint_names: List of custom names for entries in the list of coordinates,
            used for the arrival instruction in banners and voice instructions. Values can be any string, and the
            total number of all characters cannot exceed 500. If provided, the list of waypoint_names must be the
            same length as the list of coordinates. The first value in the list corresponds to the route origin, not the first
            destination.
        :type waypoint_names: list of str

        :param waypoint_targets: List of coordinate pairs used to specify drop-off locations that are distinct from the
            locations specified in coordinates. If this parameter is provided, the Directions API will compute the side
            of the street, left or right, for each target based on the waypoint_targets and the driving direction. The
            maneuver.modifier, banner and voice instructions will be updated with the computed side of street. The
            number of waypoint_targets must be the same as the number of coordinates.
        :type waypoint_targets: list of list of float

        :param dry_run: Print URL and parameters without sending the request.
        :param dry_run: bool

        :returns: One or multiple route(s) from provided coordinates and restrictions.
        :rtype: :class:`routingpy.direction.Direction` or :class:`routingpy.direction.Directions`
        """

        coords = convert._delimit_list([
            convert._delimit_list([convert._format_float(f) for f in pair])
            for pair in locations
        ], ';')

        params = {'coordinates': coords}

        if radiuses:
            params["radiuses"] = convert._delimit_list(radiuses, ';')

        if bearings:
            params["bearings"] = convert._delimit_list(
                [convert._delimit_list(pair) for pair in bearings], ';')

        if alternatives is not None:
            params["alternatives"] = convert._convert_bool(alternatives)

        if steps is not None:
            params["steps"] = convert._convert_bool(steps)

        if continue_straight is not None:
            params["continue_straight"] = convert._convert_bool(
                continue_straight)

        if annotations is not None:
            params["annotations"] = convert._delimit_list(annotations)

        if geometries:
            params["geometries"] = geometries

        if overview is not None:
            params["overview"] = convert._convert_bool(overview)

        if exclude is not None:
            params['exclude'] = exclude

        if approaches:
            params['approaches'] = ';' + convert._delimit_list(approaches, ';')

        if banner_instructions:
            params['banner_instuctions'] = convert._convert_bool(
                banner_instructions)

        if language:
            params['language'] = language

        if roundabout_exits:
            params['roundabout_exits'] = convert._convert_bool(
                roundabout_exits)

        if voice_instructions:
            params['voide_instructions'] = convert._convert_bool(
                voice_instructions)

        if voice_units:
            params['voice_units'] = voice_units

        if waypoint_names:
            params['waypoint_names'] = convert._delimit_list(
                waypoint_names, ';')

        if waypoint_targets:
            params['waypoint_targets'] = ';' + convert._delimit_list([
                convert._delimit_list([convert._format_float(f) for f in pair])
                for pair in waypoint_targets
            ], ';')

        get_params = {'access_token': self.api_key} if self.api_key else {}

        return self._parse_direction_json(
            self._request(
                "/directions/v5/mapbox/" + profile,
                get_params=get_params,
                post_params=params,
                dry_run=dry_run,
                requests_kwargs={
                    "headers": {
                        "Content-Type": 'application/x-www-form-urlencoded'
                    }
                },
            ), alternatives, geometries)
Example #18
0
    def directions(self,
                   locations,
                   profile,
                   format=None,
                   optimize=None,
                   instructions=None,
                   locale=None,
                   elevation=None,
                   points_encoded=None,
                   calc_points=None,
                   debug=None,
                   point_hint=None,
                   details=None,
                   ch_disable=None,
                   weighting=None,
                   heading=None,
                   heading_penalty=None,
                   pass_through=None,
                   block_area=None,
                   avoid=None,
                   algorithm=None,
                   round_trip_distance=None,
                   round_trip_seed=None,
                   alternative_route_max_paths=None,
                   alternative_route_max_weight_factor=None,
                   alternative_route_max_share_factor=None,
                   dry_run=None,
                   snap_prevention=None,
                   curb_side=None,
                   turn_costs=None):
        """Get directions between an origin point and a destination point.

        For more information, visit https://docs.graphhopper.com/#tag/Routing-API/paths/~1route/get.

        :param locations: The coordinates tuple the route should be calculated
            from in order of visit.
        :type locations: list of list or tuple of tuple

        :param profile: The vehicle for which the route should be calculated. One of ["car" "bike" "foot" "hike" "mtb"
            "racingbike" "scooter" "truck" "small_truck"]. Default "car".
        :type profile: str

        :param format: Specifies the resulting format of the route, for json the content type will be application/json.
            Default "json".
        :type format: str

        :param locale: Language for routing instructions. The locale of the resulting turn instructions.
            E.g. pt_PT for Portuguese or de for German. Default "en".
        :type locale: str

        :param optimize: If false the order of the locations will be identical to the order of the point parameters.
            If you have more than 2 points you can set this optimize parameter to ``True`` and the points will be sorted
            regarding the minimum overall time - e.g. suiteable for sightseeing tours or salesman.
            Keep in mind that the location limit of the Route Optimization API applies and the credit costs are higher!
            Note to all customers with a self-hosted license: this parameter is only available if your package includes
            the Route Optimization API. Default False.
        :type optimize: bool

        :param instructions: Specifies whether to return turn-by-turn instructions.
            Default True.
        :type instructions: bool

        :param elevation: If true a third dimension - the elevation - is included in the polyline or in the GeoJson.
            IMPORTANT: If enabled you have to use a modified version of the decoding method or set points_encoded to false.
            See the points_encoded attribute for more details. Additionally a request can fail if the vehicle does not
            support elevation. See the features object for every vehicle.
            Default False.
        :type elevation: bool

        :param points_encoded: If ``False`` the coordinates in point and snapped_waypoints are returned as array using the order
            [lon,lat,elevation] for every point. If true the coordinates will be encoded as string leading to less bandwith usage.
            Default True.
        :type points_encoded: bool

        :param calc_points: If the points for the route should be calculated at all, printing out only distance and time.
            Default True.
        :type calc_points: bool

        :param debug: If ``True``, the output will be formated.
            Default False.
        :type debug: bool

        :param point_hint: The point_hint is typically a road name to which the associated point parameter should be
            snapped to. Specify no point_hint parameter or the same number as you have locations. Optional.
        :type point_hint: list of str

        :param details: Optional parameter to retrieve path details. You can request additional details for the route:
            street_name, time, distance, max_speed, toll, road_class, road_class_link, road_access, road_environment,
            lanes, and surface.
        :type details: list of str

        :param ch_disable: Always use ch_disable=true in combination with one or more parameters of this table.
            Default False.
        :type ch_disable: bool

        :param weighting: Which kind of 'best' route calculation you need. Other options are shortest
            (e.g. for vehicle=foot or bike) and short_fastest if not only time but also distance is expensive.
            Default "fastest".
        :type weighting: str

        :param heading: Optional parameter. Favour a heading direction for a certain point. Specify either one heading for the start point or as
            many as there are points. In this case headings are associated by their order to the specific points.
            Headings are given as north based clockwise angle between 0 and 360 degree.
        :type heading: list of int

        :param heading_penalty: Optional parameter. Penalty for omitting a specified heading. The penalty corresponds to the accepted time
            delay in seconds in comparison to the route without a heading.
            Default 120.
        :type heading_penalty: int

        :param pass_through: Optional parameter. If true u-turns are avoided at via-points with regard to the heading_penalty.
            Default False.
        :type pass_through: bool

        :param block_area: Optional parameter. Block road access via a point with the format
            latitude,longitude or an area defined by a circle lat,lon,radius or a rectangle lat1,lon1,lat2,lon2.
        :type block_area: str

        :param avoid: Optional semicolon separated parameter. Specify which road classes you would like to avoid
            (currently only supported for motor vehicles like car). Possible values are ferry, motorway, toll, tunnel and ford.
        :type avoid: list of str

        :param algorithm: Optional parameter. round_trip or alternative_route.
        :type algorithm: str

        :param round_trip_distance: If algorithm=round_trip this parameter configures approximative length of the resulting round trip.
            Default 10000.
        :type round_trip_distance: int

        :param round_trip_seed: If algorithm=round_trip this parameter introduces randomness if e.g. the first try wasn't good.
            Default 0.
        :type round_trip_seed: int

        :param alternative_route_max_paths: If algorithm=alternative_route this parameter sets the number of maximum paths
            which should be calculated. Increasing can lead to worse alternatives.
            Default 2.
        :type alternative_route_max_paths: int

        :param alternative_route_max_weight_factor: If algorithm=alternative_route this parameter sets the factor by which the alternatives
            routes can be longer than the optimal route. Increasing can lead to worse alternatives.
            Default 1.4.
        :type alternative_route_max_weight_factor: float

        :param alternative_route_max_share_factor: If algorithm=alternative_route this parameter specifies how much alternatives
            routes can have maximum in common with the optimal route. Increasing can lead to worse alternatives.
            Default 0.6.
        :type alternative_route_max_share_factor: float

        :param dry_run: Print URL and parameters without sending the request.
        :type dry_run: bool

        :param snap_prevention: Optional parameter to avoid snapping to a certain road class or road environment.
            Currently supported values are motorway, trunk, ferry, tunnel, bridge and ford. Optional.
        :type snap_prevention: list of str

        :param curb_side: One of "any", "right", "left". It specifies on which side a point should be relative to the driver
            when she leaves/arrives at a start/target/via point. You need to specify this parameter for either none
            or all points. Only supported for motor vehicles and OpenStreetMap.
        :type curb_side: list of str

        :param turn_costs: Specifies if turn restrictions should be considered. Enabling this option increases the
            route computation time. Only supported for motor vehicles and OpenStreetMap.
        :type turn_costs: bool

        :returns: One or multiple route(s) from provided coordinates and restrictions.
        :rtype: :class:`routingpy.direction.Direction` or :class:`routingpy.direction.Directions`

        .. versionchanged:: 0.3.0
           `point_hint` used to be bool, which was not the right usage.

        .. versionadded:: 0.3.0
           ``snap_prevention``, ``curb_side``, ``turn_costs`` parameters
        """

        params = [('vehicle', profile)]

        for coordinate in locations:
            coord_latlng = reversed(
                [convert._format_float(f) for f in coordinate])
            params.append(("point", ",".join(coord_latlng)))

        if self.key is not None:
            params.append(("key", self.key))

        if format is not None:
            params.append(("type", format))

        if optimize is not None:
            params.append(("optimize", convert._convert_bool(optimize)))

        if instructions is not None:
            params.append(
                ("instructions", convert._convert_bool(instructions)))

        if locale is not None:
            params.append(("locale", locale))

        if elevation is not None:
            params.append(("elevation", convert._convert_bool(elevation)))

        if points_encoded is not None:
            params.append(
                ("points_encoded", convert._convert_bool(points_encoded)))

        if calc_points is not None:
            params.append(("calc_points", convert._convert_bool(calc_points)))

        if debug is not None:
            params.append(("debug", convert._convert_bool(debug)))

        if point_hint is not None:
            for hint in point_hint:
                params.append(("point_hint", hint))

        if snap_prevention:
            params.append(
                ('snap_prevention', convert._delimit_list(snap_prevention)))

        if turn_costs:
            params.append(('turn_costs', convert._convert_bool(turn_costs)))

        if curb_side:
            params.append(('curb_side', convert._delimit_list(curb_side)))

        ### all below params will only work if ch is disabled

        if details is not None:
            params.extend([("details", detail) for detail in details])

        if ch_disable is not None:
            params.append(("ch.disable", convert._convert_bool(ch_disable)))

        if weighting is not None:
            params.append(("weighting", weighting))

        if heading is not None:
            params.append(("heading", convert._delimit_list(heading)))

        if heading_penalty is not None:
            params.append(("heading_penalty", heading_penalty))

        if pass_through is not None:
            params.append(
                ("pass_through", convert._convert_bool(pass_through)))

        if block_area is not None:
            params.append(("block_area", block_area))

        if avoid is not None:
            params.append(("avoid", convert._delimit_list(avoid, ';')))

        if algorithm is not None:

            params.append(('algorithm', algorithm))

            if algorithm == 'round_trip':

                if round_trip_distance is not None:
                    params.append(("round_trip.distance", round_trip_distance))

                if round_trip_seed is not None:
                    params.append(("round_trip.seed", round_trip_seed))

            if algorithm == 'alternative_route':

                if alternative_route_max_paths is not None:
                    params.append(("alternative_route.max_paths",
                                   alternative_route_max_paths))

                if alternative_route_max_weight_factor is not None:
                    params.append(("alternative_route.max_weight_factor",
                                   alternative_route_max_weight_factor))

                if alternative_route_max_share_factor:
                    params.append(("alternative_route_max_share_factor",
                                   alternative_route_max_share_factor))

        return self._parse_directions_json(
            self._request('/route', get_params=params, dry_run=dry_run),
            algorithm, elevation)
Example #19
0
    def test_delimit_list(self):

        l = [(8.68864, 49.42058), (8.68092, 49.41578)]
        s = convert._delimit_list(
            [convert._delimit_list(pair, ',') for pair in l], '|')
        self.assertEqual(s, "8.68864,49.42058|8.68092,49.41578")