예제 #1
0
    def test_autocomplete_wrong_schema(self):
        ENDPOINT_DICT['pelias_autocomplete'].update({
            'layers': ['locality', 'name'],
        })

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['pelias_autocomplete'], 'pelias_autocomplete')
        em = e.exception

        self.assertIn("unallowed values ['name']", str(em))
예제 #2
0
    def test_directions_wrong_schema(self):
        ENDPOINT_DICT['directions']['preference'] = 'best'
        ENDPOINT_DICT['directions']['attributeds'] = ['avgspeed']
        ENDPOINT_DICT['directions']['radiuses'] = 2 * PARAM_LIST_ONE

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['directions'], 'directions')
        em = e.exception

        self.assertIn('unallowed value best', str(em))
        self.assertIn('unknown field', str(em))
        self.assertIn('max length is 2', str(em))
예제 #3
0
    def test_reverse_wrong_schema(self):
        ENDPOINT_DICT['pelias_reverse'].update({
            'country': 35,
            'sources': ['osm', 'wof', 'gm'],
        })

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['pelias_reverse'], 'pelias_reverse')
        em = e.exception

        self.assertIn('must be of string type', str(em))
        self.assertIn("unallowed values ['gm']", str(em))
예제 #4
0
    def test_search_wrong_schema(self):
        ENDPOINT_DICT['pelias_search'].update({
            'layers': ['locality', 'name'],
            'circle_radius': {50},
        })

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['pelias_search'], 'pelias_search')
        em = e.exception

        self.assertIn("unallowed values ['name']", str(em))
        self.assertIn('must be of integer type', str(em))
예제 #5
0
    def test_pois_wrong_schema(self):
        ENDPOINT_DICT['pois'].update({
            'geojson': {'type': 'Point'},
            'filters_custom': {'wheelchair': ['maybe']},
            'limit': 1200,
        })

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['pois'], 'pois')
        em = e.exception

        self.assertIn("field 'coordinates' is required", str(em))
        self.assertIn('max value is 1000', str(em))
        self.assertIn('unallowed value maybe', str(em))
예제 #6
0
    def test_isochrones_wrong_schema(self):
        del ENDPOINT_DICT['isochrones']['locations']
        ENDPOINT_DICT['isochrones'].update({
            'attributes': ['areas', 'reachfactor'],
            'range': ['30']
        })

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['isochrones'], 'isochrones')
        em = e.exception

        self.assertIn('required field', str(em))
        self.assertIn('unallowed value', str(em))
        self.assertIn('must be of integer type', str(em))
예제 #7
0
    def test_pois_correct_schema(self):
        validator.validator(ENDPOINT_DICT['pois'], 'pois')

        ENDPOINT_DICT['pois']['geojson'] = PARAM_GEOJSON_LINE
        validator.validator(ENDPOINT_DICT['pois'], 'pois')

        ENDPOINT_DICT['pois']['geojson'] = PARAM_GEOJSON_POLY
        validator.validator(ENDPOINT_DICT['pois'], 'pois')

        ENDPOINT_DICT['pois']['request'] = 'stats'
        validator.validator(ENDPOINT_DICT['pois'], 'pois')

        ENDPOINT_DICT['pois'] = {'request': 'list'}
        validator.validator(ENDPOINT_DICT['pois'], 'pois')
예제 #8
0
    def test_distance_matrix_wrong_schema(self):
        ENDPOINT_DICT['distance_matrix'].update({
            'sources': [0, 1, 2],
            'metrics': ['duration', 'distance'],
            'resolve_locations': 'true',
            'units': 'm',
            'optimizedd': 'false'
        })

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['distance_matrix'], 'distance_matrix')
        em = e.exception

        self.assertIn('max value is 1', str(em))
        self.assertIn('unknown field', str(em))
예제 #9
0
def elevation_line(client,
                   format_in,
                   geometry,
                   format_out='geojson',
                   dataset='srtm',
                   validate=True,
                   dry_run=None):
    """
    POSTs 2D point to be enriched with elevation.
    
    :param format_in: Format of input geometry. One of ['geojson',
        'polyline', 'encodedpolyline']
    :type format_in: string
    
    :param geometry: Point geometry 
    :type geometry: depending on format_in, either list of coordinates, LineString
        geojson or string
    
    :param format_out: Format of output geometry, one of ['geojson',
        'polyline', 'encodedpolyline']
    :type format_out: string
    
    :param dataset: Elevation dataset to be used. Currently only SRTM v4.1 available.
    :type dataset: string
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean
    
    :returns: correctly formatted parameters
    :rtype: Client.request()
    """
    if validate:
        validator.validator(locals(), 'elevation_line')

    params = {
        'format_in': format_in,
        'geometry': geometry,
        'format_out': format_out,
        'dataset': dataset
    }

    return client.request('/elevation/line', {},
                          post_json=params,
                          dry_run=dry_run)
예제 #10
0
    def test_structured_wrong_schema(self):
        ENDPOINT_DICT['pelias_structured'].update({
            'address': {'Berliner Straße 45'},
            'postalcode': '69120',
        })
        params = {
            'address': {'Berliner Straße 45'},
            'neighbourhood': 'Neuenheimer Feld',
            'borough': 'Heidelberg',
            'locality': 'Heidelberg',
            'county': 'Rhein-Neckar-Kreis',
            'region': 'Baden-Württemberg',
            'postalcode': '69120',
            'country': 'de',
        }

        with self.assertRaises(exceptions.ValidationError) as e:
            validator.validator(ENDPOINT_DICT['pelias_structured'], 'pelias_structured')
        em = e.exception

        self.assertIn('must be of integer type', str(em))
        self.assertIn('must be of string type', str(em))
예제 #11
0
def pelias_search(client, text,
                  focus_point=None,
                  rect_min_x=None,
                  rect_min_y=None,
                  rect_max_x=None,
                  rect_max_y=None,
                  circle_point=None,
                  circle_radius=None,
                  sources=None,
                  layers=None,
                  country=None,
                  size=None,
                  dry_run=None):
    """
    Geocoding is the process of converting addresses into geographic
    coordinates.

    This endpoint queries directly against a Pelias instance.

    :param text: Full-text query against search endpoint. Required.
    :type text: string

    :param focus_point: Focusses the search to be around this point and gives
        results within a 100 km radius higher scores.
    :type query: list or tuple of (Long, Lat)

    :param rect_min_x: Min longitude by which to constrain request geographically.
    :type rect_min_x: float

    :param rect_min_y: Min latitude by which to constrain request geographically.
    :type rect_min_y: float

    :param rect_max_x: Max longitude by which to constrain request geographically.
    :type rect_max_x: float

    :param rect_max_y: Max latitude by which to constrain request geographically.
    :type rect_max_y: float

    :param circle_point: Geographical constraint in form a circle.
    :type circle_point: list or tuple of (Long, Lat)

    :param circle_radius: Radius of circle constraint in km. Default 50.
    :type circle_radius: integer

    :param sources: The originating source of the data. One or more of
        ['osm', 'oa', 'wof', 'gn']. Currently only 'osm', 'wof' and 'gn' are
        supported.
    :type sources: list of strings

    :param layers: The administrative hierarchy level for the query. Refer to
        https://github.com/pelias/documentation/blob/master/search.md#filter-by-data-type
        for details.
    :type layers: list of strings

    :param country: Constrain query by country. Accepts a alpha-2 or alpha-3
        digit ISO-3166 country code.
    :type country: str

    :param size: The amount of results returned. Default 10.
    :type size: integer
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises ValueError: When parameter has invalid value(s).
    :raises TypeError: When parameter is of the wrong type.

    :rtype: call to Client.request()
    """

    validator.validator(locals(), 'pelias_search')

    params = {'text': text}

    if focus_point:
        params['focus.point.lon'] = convert._format_float(focus_point[0])
        params['focus.point.lat'] = convert._format_float(focus_point[1])

    if rect_min_x:
        params['boundary.rect.min_lon'] = convert._format_float(rect_min_x)  #

    if rect_min_y:
        params['boundary.rect.min_lat'] = convert._format_float(rect_min_y)  #

    if rect_max_x:
        params['boundary.rect.max_lon'] = convert._format_float(rect_max_x)  #

    if rect_max_y:
        params['boundary.rect.max_lat'] = convert._format_float(rect_max_y)  #

    if circle_point:
        params['boundary.circle.lon'] = convert._format_float(circle_point[0])  #
        params['boundary.circle.lat'] = convert._format_float(circle_point[1])  #

    if circle_radius:
        params['boundary.circle.radius'] = circle_radius

    if sources:
        params['sources'] = convert._comma_list(sources)

    if layers:
        params['layers'] = convert._comma_list(layers)

    if country:
        params['boundary.country'] = country

    if size:
        params['size'] = size

    return client.request("/geocode/search", params, dry_run=dry_run)
예제 #12
0
def pelias_structured(client,
                      address=None,
                      neighbourhood=None,
                      borough=None,
                      locality=None,
                      county=None,
                      region=None,
                      postalcode=None,
                      country=None,
                      dry_run=None,
                      # size=None
                      ):
    """
    With structured geocoding, you can search for the individual parts of a location.
    Structured geocoding is an option on the search endpoint,
    which allows you to define a query that maintains the individual fields.

    This endpoint queries directly against a Pelias instance.
    For full documentation, please see https://github.com/pelias/documentation/blob/master/structured-geocoding.md

    :param address: Can contain a full address with house number or only a street name.
    :type address: string

    :param neighbourhood: Neighbourhoods are vernacular geographic entities that
        may not necessarily be official administrative divisions but are important nonetheless.
    :type neighbourhood: string

    # Check all passed arguments
    convert._is_valid_args(locals())

    :param borough: Mostly known in the context of New York City, even though they may exist in other cities.
    :type borough: string

    :param locality: Localities are equivalent to what are commonly referred to as cities.
    :type locality: string

    :param county: Administrative divisions between localities and regions.
        Not as commonly used in geocoding as localities, but useful when attempting to
        disambiguate between localities.
    :type county: string

    :param region: Normally the first-level administrative divisions within countries, analogous to states
        and provinces in the United States and Canada. Can be a full name or abbreviation.
    :type region: string

    :param postalcode: Dictated by an administrative division, which is almost always countries.
        Postal codes are unique within a country.
    :type postalcode: integer

    :param country: Highest-level divisions supported in a search. Can be a full name or abbreviation.
    :type country: string
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises TypeError: When parameter is of the wrong type.

    :rtype: dict from JSON response
    """

    validator.validator(locals(), 'pelias_structured')

    params = dict()

    if address:
        params['address'] = address

    if neighbourhood:
        params['neighbourhood'] = neighbourhood

    if borough:
        params['borough'] = borough

    if locality:
        params['locality'] = locality

    if county:
        params['county'] = county

    if region:
        params['region'] = region

    if postalcode:
        params['postalcode'] = postalcode

    if country:
        params['country'] = country

    return client.request("/geocode/search/structured", params, dry_run=dry_run)
예제 #13
0
def pelias_autocomplete(client, text,
                        focus_point=None,
                        rect_min_x=None,
                        rect_min_y=None,
                        rect_max_x=None,
                        rect_max_y=None,
                        country=None,
                        sources=None,
                        layers=None,
                        dry_run=None):
    """
    Autocomplete geocoding can be used alongside /search to enable real-time feedback.
    It represents a type-ahead functionality, which helps to find the desired location,
    without to require a fully specified search term.

    This endpoint queries directly against a Pelias instance.
    For fully documentation, please see https://github.com/pelias/documentation/blob/master/autocomplete.md

    :param text: Full-text query against search endpoint. Required.
    :type text: string

    :param focus_point: Focusses the search to be around this point and gives
        results within a 100 km radius higher scores.
    :type query: list or tuple of (Long, Lat)

    :param rect_min_x: Min longitude by which to constrain request geographically.
    :type rect_min_x: float

    :param rect_min_y: Min latitude by which to constrain request geographically.
    :type rect_min_y: float

    :param rect_max_x: Max longitude by which to constrain request geographically.
    :type rect_max_x: float

    :param rect_max_y: Max latitude by which to constrain request geographically.
    :type rect_max_y: float

    :param country: Constrain query by country. Accepts a alpha-2 or alpha-3
        digit ISO-3166 country codes.
    :type country: str

    :param sources: The originating source of the data. One or more of
        ['osm', 'oa', 'wof', 'gn']. Currently only 'osm', 'wof' and 'gn' are
        supported.
    :type sources: list of strings

    :param layers: The administrative hierarchy level for the query. Refer to
        https://github.com/pelias/documentation/blob/master/search.md#filter-by-data-type
        for details.
    :type layers: list of strings
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises ValueError: When parameter has invalid value(s).
    :raises TypeError: When parameter is of the wrong type.

    :rtype: dict from JSON response
    """

    validator.validator(locals(), 'pelias_autocomplete')

    params = {'text': text}

    if focus_point:
        params['focus.point.lon'] = convert._format_float(focus_point[0])
        params['focus.point.lat'] = convert._format_float(focus_point[1])

    if rect_min_x:
        params['boundary.rect.min_lon	'] = convert._format_float(rect_min_x)

    if rect_min_y:
        params['boundary.rect.min_lat	'] = convert._format_float(rect_min_y)

    if rect_max_x:
        params['boundary.rect.max_lon	'] = convert._format_float(rect_max_x)

    if rect_max_y:
        params['boundary.rect.max_lon	'] = convert._format_float(rect_max_y)

    if country:
        params['boundary.country'] = country

    if sources:
        params['sources'] = convert._comma_list(sources)

    if layers:
        params['layers'] = convert._comma_list(layers)

    return client.request("/geocode/autocomplete", params, dry_run=dry_run)
예제 #14
0
 def test_search_correct_schema(self):
     validator.validator(ENDPOINT_DICT['pelias_search'], 'pelias_search')
예제 #15
0
 def test_distance_matrix_correct_schema(self):
     validator.validator(ENDPOINT_DICT['distance_matrix'],
                         'distance_matrix')
예제 #16
0
 def test_isochrones_correct_schema(self):
     validator.validator(ENDPOINT_DICT['isochrones'], 'isochrones')
예제 #17
0
def places(client, request,
           geojson=None,
           bbox=None,
           buffer=None,
           filter_category_ids=None,
           filter_category_group_ids=None,
           filters_custom=None,
           limit=None,
           sortby=None,
           validate=True,
           dry_run=None
           ):
    """ Gets POI's filtered by specified parameters.

    :param request: Type of request. One of ['pois', 'list', 'stats'].
        'pois': returns geojson of pois;
        'stats': returns statistics of passed categories;
        'list': returns mapping of category ID's to textual representation.
    :type request: string

    :param geojson: GeoJSON dict used for the query.
    :type geojson: dict

    :param buffer: Buffers geometry of 'geojson' or 'bbox' with the specified
        value in meters.
    :type intervals: integer

    :param filter_category_ids: Filter by ORS custom category IDs. See
        https://github.com/GIScience/openrouteservice-docs#places-response
        for the mappings.
    :type units: list of integer

    :param filter_category_group_ids: Filter by ORS custom high-level category
        groups. See
        https://github.com/GIScience/openrouteservice-docs#places-response
        for the mappings.        
    :type attributes: list of integer

    :param filters_custom: Specify additional filters by key/value. Default ORS
        filters are
        'name': free text
        'wheelchair': ['yes', 'limited', 'no', 'designated']
        'smoking': ['dedicated','yes','separated','isolated', 'no', 'outside']
        'fee': ['yes','no', 'str']
    :type filters_custom: dict of lists/str

    :param limit: limit for POI queries.
    :type limit: integer
                       base_url='http://localhost:5000'
    
    :param sortby: Sorts the returned features by 'distance' or 'category'. 
        For request='pois' only.
    :type sortby: string
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean
    
    :rtype: call to Client.request()
    """

    if validate:
        validator.validator(locals(), 'pois')

    params = {
        'request': request,
        'filters': dict(),
        'geometry': dict(),
    }

    if request != 'category_list':
        if geojson:
            params['geometry']['geojson'] = geojson

        if bbox:
            params['geometry']['bbox'] = bbox

        if buffer:
            params['geometry']['buffer'] = buffer

        if filter_category_ids and convert._is_list(filter_category_ids):
            params['filters']['category_ids'] = filter_category_ids

        if filter_category_group_ids and convert._is_list(filter_category_group_ids):
            params['filters']['category_group_ids'] = filter_category_group_ids

        if filters_custom:
            for f in filters_custom:
                params['filters'][f] = filters_custom[f]

        if limit:
            params['limit'] = limit

        if sortby:
            params['sortby'] = sortby

    return client.request('/pois', {}, post_json=params, dry_run=dry_run)
예제 #18
0
def directions(
        client,
        coordinates,
        profile='driving-car',
        format_out=None,
        preference=None,
        units=None,
        language=None,
        geometry=None,
        geometry_format=None,
        geometry_simplify=None,
        instructions=None,
        instructions_format=None,
        roundabout_exits=None,
        attributes=None,
        # maneuvers=None,
        radiuses=None,
        bearings=None,
        continue_straight=None,
        elevation=None,
        extra_info=None,
        optimized=True,
        options=None,
        dry_run=None):
    """Get directions between an origin point and a destination point.

    For more information, visit https://go.openrouteservice.org/documentation/.

    :param coordinates: The coordinates tuple the route should be calculated
        from. In order of visit.
    :type origin: list or tuple of coordinate lists or tuples

    :param profile: Specifies the mode of transport to use when calculating
        directions. One of ["driving-car", "driving-hgv", "foot-walking",
        "foot-hiking", "cycling-regular", "cycling-road",requests_kwargs
        "cycling-safe", "cycling-mountain", "cycling-tour",
        "cycling-electric",]. Default "driving-car".
    :type mode: string

    :param preference: Specifies the routing preference. One of ["fastest, "shortest",
        "recommended"]. Default "fastest".
    :type preference: string

    :param units: Specifies the distance unit. One of ["m", "km", "mi"]. Default "m".
    :type units: string

    :param language: Language for routing instructions. One of ["en", "de", "cn",
        "es", "ru", "dk", "fr", "it", "nl", "br", "se", "tr", "gr"]. Default "en".
    :type language: string

    :param language: The language in which to return results.
    :type language: string

    :param geometry: Specifies whether geometry should be returned. Default True.
    :type geometry: boolean

    :param geometry_format: Specifies which geometry format should be returned.
        One of ["encodedpolyline", "geojson", "polyline"]. Default: "encodedpolyline".
    :type geometry_format: string

    :param geometry_simplify: Specifies whether to simplify the geometry.
        Default False.
    :type geometry_simplify: boolean

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

    :param instructions_format: Specifies the the output format for instructions.
        One of ["text", "html"]. Default "text".
    :type instructions_format: string

    :param roundabout_exits: Provides bearings of the entrance and all passed
        roundabout exits. Adds the 'exit_bearings' array to the 'step' object
        in the response. Default False.
    :type roundabout_exits: boolean

    :param attributes: Returns route attributes on ["avgspeed", "detourfactor", "percentage"].
        Must be a list of strings. Default None.
    :type attributes: list or tuple of strings

    :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, the value of -1 specifies no limit in
        the search. The number of radiuses must correspond to the number of waypoints.
        Default None.
    :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. Setting optimized=false is mandatory for this feature to
        work for all profiles. The number of bearings corresponds to the length
        of waypoints-1 or waypoints. If the bearing information for the last waypoint
        is given, then this will control the sector from which the destination
        waypoint may be reached.
    :type bearings: list or tuple or lists or tuples

    :param continue_straight: Forces the route to keep going straight at waypoints
        restricting u-turns even if u-turns would be faster. This setting
        will work for all profiles except for driving-*. In this case you will
        have to set optimized=false for it to work. True or False. Default False.
    :type continue_straight: boolean

    :param elevation: Specifies whether to return elevation values for points.
        Default False.
    :type elevation: boolean

    :param extra_info: Returns additional information on ["steepness", "suitability",
        "surface", "waycategory", "waytype", "tollways", "traildifficulty"].
        Must be a list of strings. Default None.
    :type extra_info: list or tuple of strings

    :param optimized: If set True, uses Contraction Hierarchies.
        Default True.
    :type optimized: boolean

    :param options: Refer to https://go.openrouteservice.org/documentation for
        detailed documentation. Construct your own dict() following the example
        of the minified options object. Will be converted to json automatically.
    :type options: dict
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises ValueError: When parameter has wrong value.
    :raises TypeError: When parameter is of wrong type.

    :returns: sanitized set of pararmeters
    :rtype: call to Client.request()
    """

    validator.validator(locals(), 'directions')

    params = {"coordinates": convert._build_coords(coordinates)}

    if profile:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        params["profile"] = profile

    if format_out:
        params["format"] = format_out

    if preference:
        params["preference"] = preference

    if units:
        params["units"] = units

    if language:
        params["language"] = language

    if geometry is not None:
        # not checked on backend, check here
        params["geometry"] = convert._convert_bool(geometry)

    if geometry_format:
        params["geometry_format"] = geometry_format

    if geometry_simplify is not None:
        # not checked on backend, check here
        if extra_info:
            params["geometry_simplify"] = 'false'
        else:
            params["geometry_simplify"] = convert._convert_bool(
                geometry_simplify)

    if instructions is not None:
        # not checked on backend, check here
        params["instructions"] = convert._convert_bool(instructions)

    if instructions_format:
        params["instructions_format"] = instructions_format

    if roundabout_exits is not None:
        # not checked on backend, check here
        params["roundabout_exits"] = convert._convert_bool(roundabout_exits)

    if attributes:
        # not checked on backend, check here
        params["attributes"] = convert._pipe_list(attributes)

    if radiuses:
        params["radiuses"] = convert._pipe_list(radiuses)

    if bearings:
        params["bearings"] = convert._pipe_list(
            [convert._comma_list(pair) for pair in bearings])

    if continue_straight is not None:
        # not checked on backend, check here
        params["continue_straight"] = convert._convert_bool(continue_straight)

    if elevation is not None:
        # not checked on backend, check here
        params["elevation"] = convert._convert_bool(elevation)

    if extra_info:
        # not checked on backend, check here
        params["extra_info"] = convert._pipe_list(extra_info)

    if optimized is not None:
        # not checked on backend, check here
        if bearings or continue_straight in (True, 'true'):
            params["optimized"] = 'false'
            print(
                "Set optimized='false' due to incompatible parameter settings."
            )
        else:
            params["optimized"] = convert._convert_bool(optimized)

    if options:
        params['options'] = json.dumps(options)

    return client.request("/directions", params, dry_run=dry_run)
예제 #19
0
 def test_reverse_correct_schema(self):
     validator.validator(ENDPOINT_DICT['pelias_reverse'], 'pelias_reverse')
예제 #20
0
 def test_structured_correct_schema(self):
     validator.validator(ENDPOINT_DICT['pelias_structured'],
                         'pelias_structured')
예제 #21
0
 def test_autocomplete_correct_schema(self):
     validator.validator(ENDPOINT_DICT['pelias_autocomplete'],
                         'pelias_autocomplete')
예제 #22
0
def directions(client,
               coordinates,
               profile='driving-car',
               format_out=None,
               format='json',
               preference=None,
               units=None,
               language=None,
               geometry=None,
               geometry_simplify=None,
               instructions=None,
               instructions_format=None,
               roundabout_exits=None,
               attributes=None,
               maneuvers=None,
               radiuses=None,
               bearings=None,
               continue_straight=None,
               elevation=None,
               extra_info=None,
               suppress_warnings=None,
               optimized=None,
               options=None,
               validate=True,
               dry_run=None):
    """Get directions between an origin point and a destination point.

    For more information, visit https://go.openrouteservice.org/documentation/.

    :param coordinates: The coordinates tuple the route should be calculated
        from. In order of visit.
    :type origin: list or tuple of coordinate lists or tuples

    :param profile: Specifies the mode of transport to use when calculating
        directions. One of ["driving-car", "driving-hgv", "foot-walking",
        "foot-hiking", "cycling-regular", "cycling-road","cycling-mountain",
        "cycling-electric",]. Default "driving-car".
    :type mode: string

    :param format: Specifies the response format. One of ['json', 'geojson', 'gpx']. Default "json".
        Geometry format for "json" is Google's encodedpolyline. The GPX schema the response is validated
        against can be found here:
        https://raw.githubusercontent.com/GIScience/openrouteservice-schema/master/gpx/v1/ors-gpx.xsd.
    :type format: str

    :param format_out: DEPRECATED.
    :type format: str

    :param preference: Specifies the routing preference. One of ["fastest, "shortest",
        "recommended"]. Default "fastest".
    :type preference: string

    :param units: Specifies the distance unit. One of ["m", "km", "mi"]. Default "m".
    :type units: string

    :param language: Language for routing instructions. One of ["en", "de", "cn",
        "es", "ru", "dk", "fr", "it", "nl", "br", "se", "tr", "gr"]. Default "en".
    :type language: string

    :param language: The language in which to return results.
    :type language: string

    :param geometry: Specifies whether geometry should be returned. Default True.
    :type geometry: boolean

    :param geometry_simplify: Specifies whether to simplify the geometry.
        Default False.
    :type geometry_simplify: boolean

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

    :param instructions_format: Specifies the the output format for instructions.
        One of ["text", "html"]. Default "text".
    :type instructions_format: string

    :param roundabout_exits: Provides bearings of the entrance and all passed
        roundabout exits. Adds the 'exit_bearings' array to the 'step' object
        in the response. Default False.
    :type roundabout_exits: boolean

    :param attributes: Returns route attributes on ["detourfactor", "percentage"].
        Must be a list of strings. Default None.
    :type attributes: list or tuple of strings

    :param maneuvers: Specifies whether the maneuver object is included into the step object or not. Default: false.
    :type maneuvers bool

    :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, the value of -1 specifies no limit in
        the search. The number of radiuses must correspond to the number of waypoints.
        Default None.
    :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. Setting optimized=false is mandatory for this feature to
        work for all profiles. The number of bearings corresponds to the length
        of waypoints-1 or waypoints. If the bearing information for the last waypoint
        is given, then this will control the sector from which the destination
        waypoint may be reached.
    :type bearings: list or tuple or lists or tuples

    :param continue_straight: Forces the route to keep going straight at waypoints
        restricting u-turns even if u-turns would be faster. This setting
        will work for all profiles except for driving-*. In this case you will
        have to set optimized=false for it to work. True or False. Default False.
    :type continue_straight: boolean

    :param elevation: Specifies whether to return elevation values for points.
        Default False.
    :type elevation: boolean

    :param extra_info: Returns additional information on ["steepness", "suitability",
        "surface", "waycategory", "waytype", "tollways", "traildifficulty", "roadaccessrestrictions"].
        Must be a list of strings. Default None.
    :type extra_info: list or tuple of strings

    :param suppress_warnings: Tells the system to not return any warning messages and corresponding extra_info.
        For false the extra information can still be explicitly requested by adding it with the extra_info parameter.
    :type suppress_warnings: bool

    :param optimized: If set False, forces to not use Contraction Hierarchies.
    :type optimized: bool

    :param options: Refer to https://go.openrouteservice.org/documentation for
        detailed documentation. Construct your own dict() following the example
        of the minified options object. Will be converted to json automatically.
    :type options: dict

    :param validate: Specifies whether parameters should be validated before sending the request. Default True.
    :type validate: bool
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises ValueError: When parameter has wrong value.
    :raises TypeError: When parameter is of wrong type.

    :returns: sanitized set of parameters
    :rtype: call to Client.request()
    """

    if validate:
        validator.validator(locals(), 'directions')

    params = {"coordinates": coordinates}

    if format_out:
        deprecation.warning('format_out', 'format')

    format = format_out or format

    if preference:
        params["preference"] = preference

    if units:
        params["units"] = units

    if language:
        params["language"] = language

    if geometry is not None:
        params["geometry"] = geometry

    if geometry_simplify is not None:
        # not checked on backend, check here
        if extra_info:
            params["geometry_simplify"] = False
        else:
            params["geometry_simplify"] = geometry_simplify

    if instructions is not None:
        params["instructions"] = instructions

    if instructions_format:
        params["instructions_format"] = instructions_format

    if roundabout_exits is not None:
        params["roundabout_exits"] = roundabout_exits

    if attributes:
        params["attributes"] = attributes

    if radiuses:
        params["radiuses"] = radiuses

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

    if bearings:
        params["bearings"] = bearings

    if continue_straight is not None:
        params["continue_straight"] = continue_straight

    if elevation is not None:
        params["elevation"] = elevation

    if extra_info:
        params["extra_info"] = extra_info

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

    if optimized is not None:
        if (bearings or continue_straight) and optimized in (True, 'true'):
            params["optimized"] = 'false'
            print(
                "Set optimized='false' due to incompatible parameter settings."
            )
        else:
            params["optimized"] = optimized

    if options:
        params['options'] = options

    return client.request("/v2/directions/" + profile + '/' + format, {},
                          post_json=params,
                          dry_run=dry_run)
예제 #23
0
def distance_matrix(client,
                    locations,
                    profile='driving-car',
                    sources=None,
                    destinations=None,
                    metrics=None,
                    resolve_locations=None,
                    units=None,
                    optimized=None,
                    validate=True,
                    dry_run=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param locations: One or more pairs of lng/lat values.
    :type locations: a single location, or a list of locations, where a
        location is a list or tuple of lng,lat values

    :param profile: Specifies the mode of transport to use when calculating
        directions. One of ["driving-car", "driving-hgv", "foot-walking",
        "foot-hiking", "cycling-regular", "cycling-road",
        "cycling-safe", "cycling-mountain", "cycling-tour", 
        "cycling-electric",]. Default "driving-car".
    :type profile: string

    :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 metrics: Specifies a list of returned metrics. One or more of ["distance",
        "duration"]. Default ['duration'].
    :type metrics: list of strings

    :param resolve_locations: Specifies whether given locations are resolved or
        not. If set 'true', every element in destinations and sources will 
        contain the name element that identifies the name of the closest street.
        Default False.
    :type resolve_locations: boolean

    :param units: Specifies the unit system to use when displaying results.
        One of ["m", "km", "m"]. Default "m".
    :type units: string

    :param optimized: Specifies whether Dijkstra algorithm ('false') or any 
        available technique to speed up shortest-path routing ('true') is used. 
        For normal Dijkstra the number of visited nodes is limited to 100000.
        Default True
    :type optimized: boolean

    :param validate: Specifies whether parameters should be validated before sending the request. Default True.
    :type validate: bool
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean
    
    :raises ValueError: When profile parameter has wrong value.
    
    :rtype: call to Client.request()
    """

    if validate:
        validator.validator(locals(), 'distance_matrix')

    params = {
        "locations": locations,
    }

    if sources:
        params['sources'] = sources

    if destinations:
        params['destinations'] = destinations

    if profile:
        params["profile"] = profile

    if sources:
        params["sources"] = sources

    if destinations:
        params["destinations"] = destinations

    if metrics:
        params["metrics"] = metrics

    if resolve_locations is not None:
        params["resolve_locations"] = resolve_locations

    if units:
        params["units"] = units

    if optimized is not None:
        params["optimized"] = optimized

    return client.request("/v2/matrix/" + profile + '/json', {},
                          post_json=params,
                          dry_run=dry_run)
예제 #24
0
def isochrones(client, locations,
               profile='driving-car',
               range_type='time',
               range=None,
               intervals=None,
               segments=None,
               interval=None,
               units=None,
               location_type=None,
               smoothing=None,
               attributes=None,
               validate=True,
               dry_run=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param locations: One pair of lng/lat values.
    :type locations: list or tuple of lng,lat values

    :param profile: Specifies the mode of transport to use when calculating
        directions. One of ["driving-car", "driving-hgv", "foot-walking",
        "foot-hiking", "cycling-regular", "cycling-road", "cycling-mountain",
        "cycling-electric",]. Default "driving-car".
    :type profile: string

    :param range_type: Set 'time' for isochrones or 'distance' for equidistants.
        Default 'time'.
    :type sources: string

    :param intervals: [SOON DEPRECATED] replaced by `range`.
    :type intervals: list of integer(s)

    :param range: Ranges to calculate distances/durations for. This can be
        a list of multiple ranges, e.g. [600, 1200, 1400] or a single value list.
        In the latter case, you can also specify the 'interval' variable to break
        the single value into more isochrones. In meters or seconds.
    :type range: list of integer(s)

    :param segments: [SOON DEPRECATED] replaced by `interval`.
    :type segments: integer

    :param interval: Segments isochrones or equidistants for one 'range' value.
        Only has effect if used with a single value 'range' value.
        In meters or seconds.
    :type interval: integer

    :param units: Specifies the unit system to use when displaying results.
        One of ["m", "km", "m"]. Default "m".
    :type units: string
    
    :param location_type: 'start' treats the location(s) as starting point,
        'destination' as goal. Default 'start'.
    :type location_type: string

    :param smoothing: Applies a level of generalisation to the isochrone polygons generated.
        Value between 0 and 1, whereas a value closer to 1 will result in a more generalised shape.
    :type smoothing: float

    :param attributes: 'area' returns the area of each polygon in its feature
        properties. 'reachfactor' returns a reachability score between 0 and 1.
        'total_pop' returns population statistics from https://ghsl.jrc.ec.europa.eu/about.php.
        One or more of ['area', 'reachfactor', 'total_pop']. Default 'area'.
    :type attributes: list of string(s)

    :param validate: Specifies whether parameters should be validated before sending the request. Default True.
    :type validate: bool
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean
    
    :raises ValueError: When parameter has invalid value(s).
    
    :rtype: call to Client.request()
    """

    if validate:
        validator.validator(locals(), 'isochrones')

    params = {
        "locations": locations
    }

    if profile:
        params["profile"] = profile

    if range_type:
        params["range_type"] = range_type

    if intervals:
        deprecation.warning('intervals', 'range')

    range = range or intervals
    params['range'] = range

    if segments:
        deprecation.warning('segments', 'interval')

    interval = interval or segments
    if interval:
        params['interval'] = interval

    if units:
        params["units"] = units

    if location_type:
        params["location_type"] = location_type

    if smoothing:
        params["smoothing"] = smoothing

    if attributes:
        params["attributes"] = attributes

    return client.request("/v2/isochrones/" + profile + '/geojson', {}, post_json=params, dry_run=dry_run)
예제 #25
0
def pelias_reverse(client, point,
                   circle_radius=None,
                   sources=None,
                   layers=None,
                   country=None,
                   size=None,
                   dry_run=None):
    """
    Reverse geocoding is the process of converting geographic coordinates into a
    human-readable address.

    This endpoint queries directly against a Pelias instance.

    :param point: Coordinate tuple. Required.
    :type point: list or tuple of [Lon, Lat]

    :param circle_radius: Radius around point to limit query in km. Default 1.
    :type circle_radius: integer

    :param sources: The originating source of the data. One or more of
        ['osm', 'oa', 'wof', 'gn']. Currently only 'osm', 'wof' and 'gn' are
        supported.
    :type sources: list of strings

    :param layers: The administrative hierarchy level for the query. Refer to
        https://github.com/pelias/documentation/blob/master/search.md#filter-by-data-type
        for details.
    :type layers: list of strings

    :param country: Constrain query by country. Accepts a alpha-2 or alpha-3
        digit ISO-3166 country codes.
    :type country: str

    :param size: The amount of results returned. Default 10.
    :type size: integer
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean

    :raises ValueError: When parameter has invalid value(s).

    :rtype: dict from JSON response
    """

    validator.validator(locals(), 'pelias_reverse')

    params = dict()

    params['point.lon'] = convert._format_float(point[0])
    params['point.lat'] = convert._format_float(point[1])

    if circle_radius:
        params['boundary.circle.radius'] = str(circle_radius)

    if sources:
        params['sources'] = convert._comma_list(sources)

    if layers:
        params['layers'] = convert._comma_list(layers)

    if country:
        params['boundary.country'] = country

    if size:
        params['size'] = size

    return client.request("/geocode/reverse", params, dry_run=dry_run)
예제 #26
0
def isochrones(
        client,
        locations,
        profile='driving-car',
        range_type='time',
        intervals=None,
        segments=None,
        units=None,
        location_type=None,
        smoothing=None,
        attributes=None,
        # options=None,
        intersections=None,
        dry_run=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param locations: One pair of lng/lat values.
    :type locations: list or tuple of lng,lat values

    :param profile: Specifies the mode of transport to use when calculating
        directions. One of ["driving-car", "driving-hgv", "foot-walking",
        "foot-hiking", "cycling-regular", "cycling-road",
        "cycling-safe", "cycling-mountain", "cycling-tour", 
        "cycling-electric",]. Default "driving-car".
    :type profile: string

    :param range_type: Set 'time' for isochrones or 'distance' for equidistants.
        Default 'time'.
    :type sources: string

    :param intervals: Ranges to calculate distances/durations for. This can be
        a list of multiple ranges, e.g. [600, 1200, 1400] or a single value list.
        In the latter case, you can also specify the 'segments' variable to break
        the single value into more isochrones. In meters or seconds. Default [60].
    :type intervals: list of integer(s)

    :param segments: Segments isochrones or equidistants for one 'intervals' value.
        Only has effect if used with a single value 'intervals' parameter.
        In meters or seconds. Default 20.
    :type segments: integer

    :param units: Specifies the unit system to use when displaying results.
        One of ["m", "km", "m"]. Default "m".
    :type units: string
    
    :param location_type: 'start' treats the location(s) as starting point,
        'destination' as goal. Default 'start'.
    :type location_type: string

    :param smoothing: Applies a level of generalisation to the isochrone polygons generated.
        Value between 0 and 1, whereas a value closer to 1 will result in a more generalised shape.
    :type smoothing: float

    :param attributes: 'area' returns the area of each polygon in its feature
        properties. 'reachfactor' returns a reachability score between 0 and 1.
        'total_pop' returns population statistics from https://ghsl.jrc.ec.europa.eu/about.php.
        One or more of ['area', 'reachfactor', 'total_pop']. Default 'area'.
    :type attributes: list of string(s)

    :param options: not implemented right now.
    :type options: dict
    
    :param intersections: not implented right now.
    :type intersections: boolean
    
    :param dry_run: Print URL and parameters without sending the request.
    :param dry_run: boolean
    
    :raises ValueError: When parameter has invalid value(s).
    
    :rtype: call to Client.request()
    """

    validator.validator(locals(), 'isochrones')

    params = {"locations": convert._build_coords(locations)}

    if profile:
        params["profile"] = profile

    if range_type:
        params["range_type"] = range_type

    if intervals:
        params["range"] = convert._comma_list(intervals)

    if segments:
        params["interval"] = str(segments)

    if units:
        # if units and (range_type == None or range_type == 'time'):
        #     raise ValueError("For range_type time, units cannot be specified.")
        params["units"] = units

    if location_type:
        params["location_type"] = location_type

    if smoothing:
        params["smoothing"] = convert._format_float(smoothing)

    if attributes:
        params["attributes"] = convert._pipe_list(attributes)

    return client.request("/isochrones", params, dry_run=dry_run)
예제 #27
0
 def test_directions_correct_schema(self):
     validator.validator(ENDPOINT_DICT['directions'], 'directions')