Exemplo n.º 1
0
    def matrix(self,
               locations,
               profile,
               sources=None,
               destinations=None,
               out_array=['times', 'distances'],
               debug=None,
               dry_run=None):
        """ Gets travel distance and time for a matrix of origins and destinations.

        For more details visit https://docs.graphhopper.com/#tag/Matrix-API.

        :param locations: Specifiy multiple points for which the weight-, route-, time- or distance-matrix should be calculated.
            In this case the starts are identical to the destinations.
            If there are N points, then NxN entries will be calculated.
            The order of the point parameter is important. Specify at least three points.
            Is a string with the format latitude,longitude.
        :type locations: List[List[float]|Tuple[float]]|Tuple[List[float]|Tuple[float]]

        :param profile: Specifies the mode of transport.
            One of bike, car, foot or
            https://graphhopper.com/api/1/docs/supported-vehicle-profiles/Default.
            Default "car".
        :type profile: str

        :param sources: The starting points for the routes.
            Specifies an index referring to locations.
        :type sources: List[int]

        :param destinations: The destination points for the routes. Specifies an index referring to locations.
        :type destinations: List[int]

        :param out_array: Specifies which arrays should be included in the response. Specify one or more of the following
            options 'weights', 'times', 'distances'.
            The units of the entries of distances are meters, of times are seconds and of weights is arbitrary and it can differ
            for different vehicles or versions of this API.
            Default ["times", "distance"].
        :type out_array: List[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 = [('vehicle', profile)]

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

        if sources is None and destinations is None:
            locations = (reversed([convert._format_float(f) for f in coord])
                         for coord in locations)
            params.extend([('point', ",".join(coord)) for coord in locations])

        else:
            sources_out = locations
            destinations_out = locations
            try:
                sources_out = []
                for idx in sources:
                    sources_out.append(locations[idx])
            except IndexError:
                raise IndexError(
                    "Parameter sources out of locations range at index {}.".
                    format(idx))
            except TypeError:
                # Raised when sources == None
                pass
            try:
                destinations_out = []
                for idx in destinations:
                    destinations_out.append(locations[idx])
            except IndexError:
                raise IndexError(
                    "Parameter destinations out of locations range at index {}."
                    .format(idx))
            except TypeError:
                # Raised when destinations == None
                pass

            sources_out = (reversed([convert._format_float(f) for f in coord])
                           for coord in sources_out)
            params.extend([("from_point", ",".join(coord))
                           for coord in sources_out])

            destinations_out = (reversed(
                [convert._format_float(f) for f in coord])
                                for coord in destinations_out)
            params.extend([("to_point", ",".join(coord))
                           for coord in destinations_out])

        if out_array is not None:
            for e in out_array:
                params.append(("out_array", e))

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

        return self._parse_matrix_json(
            self._request('/matrix', get_params=params, dry_run=dry_run), )
Exemplo n.º 2
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)
Exemplo n.º 3
0
    def isochrones(self,
                   locations,
                   profile,
                   intervals,
                   type='json',
                   buckets=1,
                   interval_type=None,
                   reverse_flow=None,
                   debug=None,
                   dry_run=None):
        """Gets isochrones or equidistants for a range of time/distance values around a given set of coordinates.

        For mroe details visit https://docs.graphhopper.com/#tag/Isochrone-API.

        :param locations: One coordinate pair denoting the location.
        :type locations: tuple of float or list of float

        :param profile: Specifies the mode of transport.
            One of "car" "bike" "foot" "hike" "mtb" "racingbike" "scooter" "truck" "small_truck". Default "car".
        :type profile: str

        :param intervals: Maximum range to calculate distances/durations for. You can also specify
            the ``buckets`` variable to break the single value into more isochrones. For compatibility reasons,
            this parameter is expressed as list. In meters or seconds depending on `interval_type`.
        :type intervals: list of int or tuple of int

        :param interval_type: Set ``time`` for isochrones or ``distance`` for equidistants.
            Default 'time'.
        :type interval_type: str

        :param buckets: For how many sub intervals an additional polygon should be calculated.
            Default 1.
        :type buckets: int

        :param reverse_flow: If false the flow goes from point to the polygon,
            if true the flow goes from the polygon "inside" to the point.
            Default False.
        :param reverse_flow: bool

        :param debug: If true, the output will be formatted.
            Default False
        :type debug: bool

        :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 = [('vehicle', profile), ('type', type)]

        if convert._is_list(intervals):
            if interval_type in (None, 'time'):
                params.append(('time_limit', intervals[0]))
            elif interval_type == 'distance':
                params.append(('distance_limit', intervals[0]))
        else:
            raise TypeError(
                "Parameter range={} must be of type list or tuple".format(
                    range))

        center = [convert._format_float(f) for f in locations]
        center.reverse()
        params.append(("point", ",".join(center)))

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

        if buckets is not None:
            params.append(('buckets', buckets))

        if reverse_flow is not None:
            params.append(
                ('reverse_flow', convert._convert_bool(reverse_flow)))

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

        return self._parse_isochrone_json(
            self._request("/isochrone", get_params=params, dry_run=dry_run),
            type, intervals[0], buckets, center)
Exemplo n.º 4
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)
Exemplo n.º 5
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))
Exemplo n.º 6
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)
Exemplo n.º 7
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))