コード例 #1
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 alpha-2 or alpha-3 
        digit ISO-3166 country codes.
    :type country: list of strings

    :param size: The amount of results returned. Default 10.
    :type size: integer
    
    :raises ValueError: When parameter has invalid value(s).
    :raises TypeError: When parameter is of the wrong type.

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

    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:
        if not convert._is_list(sources):
            raise TypeError('Data source invalid.')
        if not all((source in valid_sources) for source in sources):
            raise ValueError(
                "Source must be one or more of {}".format(valid_sources))
        params['sources'] = convert._comma_list(sources)

    if layers:
        if not convert._is_list(layers):
            raise TypeError('Invalid layer type for geocoding.')
        if not all((layer in valid_layers) for layer in layers):
            raise ValueError(
                "Source must be one or more of ".format(valid_layers))
        params['layers'] = convert._comma_list(layers)

    if country:
        if not isinstance(country, str):
            raise TypeError('Country must be a string.')
        params['country'] = country

    if size:
        params['size'] = size

    return client.request("/geocode/search", params, dry_run=dry_run)
コード例 #2
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. "true" or "false".
        Default "true".
    :type geometry: string

    :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. 
        "true" or "false". Default "false".
    :type geometry_simplify: boolean as string

    :param instructions: Specifies whether to return turn-by-turn instructions.
        "true" or "false". Default "true".
    :type instructions: string

    :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. "true" or "false". Default "false".
    :type roundabout_exits: string

    :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.
        "true" or "false". Default "false".
    :type elevation: boolean as string

    :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. "true" or "false".
        Default "true".
    :type optimized: boolean as string

    :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
    
    :raises ValueError: When parameter has wrong value.
    :raises TypeError: When parameter is of wrong type.
    
    :rtype: call to Client.request()
    """

    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.
        if profile not in [
                "driving-car",
                "driving-hgv",
                "foot-walking",
                "foot-hiking",
                "cycling-regular",
                "cycling-road",
                "cycling-safe",
                "cycling-mountain",
                "cycling-tour",
                "cycling-electric",
        ]:
            raise ValueError("Invalid travel mode.")
        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:
        # not checked on backend, check here
        convert._checkBool(geometry)
        params["geometry"] = geometry

    if geometry_format:
        params["geometry_format"] = geometry_format

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

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

    if instructions_format:
        params["instructions_format"] = instructions_format

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

    if radiuses:
        if len(radiuses) != len(coordinates):
            raise ValueError(
                "Amount of radiuses must match the number of waypoints.")
        params["radiuses"] = convert._pipe_list(radiuses)

    if bearings:
        if len(bearings) != len(coordinates) and len(
                bearings) != len(coordinates) - 1:
            raise ValueError(
                "Provide as many bearings as waypoints or one less.")
        if not convert._is_list(bearings):
            raise TypeError("Expected a list or tuple of bearing pairs, "
                            "but got {}".format(type(bearings).__name__))
        if not all(convert._is_list(t) for t in bearings):
            raise TypeError("Expected bearing pairs to be a list or tuple")

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

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

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

    if extra_info:
        # not checked on backend, check here
        opts = [
            "steepness", "suitability", "surface", "waycategory", "waytype",
            "tollways", "traildifficulty"
        ]
        if not all((info in opts) for info in extra_info):
            raise ValueError("Contains invalid extra_info parameter(s).")

        params["extra_info"] = convert._pipe_list(extra_info)

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

    if options:
        # check if valid dict
        if not isinstance(options, dict):
            raise TypeError(
                "Expected options object to be a dict, but got {}".format(
                    type(options)))
        params['options'] = json.dumps(options)

    return client.request("/directions", params, dry_run=dry_run)
コード例 #3
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 alpha-2 or alpha-3 
        digit ISO-3166 country codes.
    :type country: list of strings

    :param size: The amount of results returned. Default 10.
    :type size: integer
    
    :raises ValueError: When parameter has invalid value(s).

    :rtype: dict from JSON response
    """

    params = dict()

    if not convert._is_list(point):
        raise TypeError('Point must be a list/tuple of coordinates.')

    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:
        if not convert._is_list(sources):
            raise TypeError('Data source invalid.')
        if not all((source in valid_sources) for source in sources):
            raise ValueError(
                "Source must be one or more of {}".format(valid_sources))
        params['sources'] = convert._comma_list(sources)

    if layers:
        if not convert._is_list(layers):
            raise TypeError('Invalid layer type for geocoding.')
        if not all((layer in valid_layers) for layer in layers):
            raise ValueError(
                "Source must be one or more of ".format(valid_layers))
        params['layers'] = convert._comma_list(layers)

    if country:
        if not isinstance(country, str):
            raise TypeError('Country must be a string.')

        params['country'] = country

    if size:
        params['size'] = size

    return client.request("/geocode/reverse", params, dry_run=dry_run)
コード例 #4
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)