Пример #1
0
def reverse_geocode(client, latlng, result_type=None, location_type=None,
                    language=None):
    """
    Reverse geocoding is the process of converting geographic coordinates into a
    human-readable address.

    :param latlng: The latitude/longitude value for which you wish to obtain the
        closest, human-readable address.
    :type latlng: string, dict, list, or tuple

    :param result_type: One or more address types to restrict results to.
    :type result_type: string or list of strings

    :param location_type: One or more location types to restrict results to.
    :type location_type: list of strings

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

    :rtype: list of reverse geocoding results.
    """

    params = {"latlng": convert.latlng(latlng)}

    if result_type:
        params["result_type"] = convert.join_list("|", result_type)

    if location_type:
        params["location_type"] = convert.join_list("|", location_type)

    if language:
        params["language"] = language

    return client._get("/maps/api/geocode/json", params)["results"]
def reverse_geocode(client, latlng, result_type=None, location_type=None,
                    language=None):
    """
    Reverse geocoding is the process of converting geographic coordinates into a
    human-readable address.
    :param latlng: The latitude/longitude value or place_id for which you wish
        to obtain the closest, human-readable address.
    :type latlng: string, dict, list, or tuple
    :param result_type: One or more address types to restrict results to.
    :type result_type: string or list of strings
    :param location_type: One or more location types to restrict results to.
    :type location_type: list of strings
    :param language: The language in which to return results.
    :type language: string
    :rtype: list of reverse geocoding results.
    """

    # Check if latlng param is a place_id string.
    #  place_id strings do not contain commas; latlng strings do.
    if convert.is_string(latlng) and ',' not in latlng:
        params = {"place_id": latlng}
    else:
        params = {"latlng": convert.latlng(latlng)}

    if result_type:
        params["result_type"] = convert.join_list("|", result_type)

    if location_type:
        params["location_type"] = convert.join_list("|", location_type)

    if language:
        params["language"] = language

    return client._request("/maps/api/geocode/json", params).get("results", [])
Пример #3
0
    def directions(client, origin, destination,
                   mode=None, waypoints=None, alternatives=False, avoid=None,
                   language=None, units=None, region=None, departure_time=None,
                   arrival_time=None, optimize_waypoints=True, transit_mode=None,
                   transit_routing_preference=None, traffic_model=None):

        params = {
            "origin": convert.latlng(origin),
            "destination": convert.latlng(destination)
        }

        if mode:
            # NOTE(broady): the mode parameter is not validated by the Maps API
            # server. Check here to prevent silent failures.
            if mode not in ["driving", "walking", "bicycling", "transit"]:
                raise ValueError("Invalid travel mode.")
            params["mode"] = mode

        if waypoints:
            waypoints = convert.location_list(waypoints)
            if optimize_waypoints:
                waypoints = "optimize:true|" + waypoints
            params["waypoints"] = waypoints

        if alternatives:
            params["alternatives"] = "true"

        if avoid:
            params["avoid"] = convert.join_list("|", avoid)

        if language:
            params["language"] = language

        if units:
            params["units"] = units

        if region:
            params["region"] = region

        if departure_time:
            params["departure_time"] = convert.time(departure_time)

        if arrival_time:
            params["arrival_time"] = convert.time(arrival_time)

        if departure_time and arrival_time:
            raise ValueError("Should not specify both departure_time and"
                             "arrival_time.")

        if transit_mode:
            params["transit_mode"] = convert.join_list("|", transit_mode)

        if transit_routing_preference:
            params["transit_routing_preference"] = transit_routing_preference

        if traffic_model:
            params["traffic_model"] = traffic_model

        return client._get("/maps/api/directions/json", params)["routes"][0]['waypoint_order']
Пример #4
0
    def test_join_list(self):
        self.assertEqual("asdf", convert.join_list("|", "asdf"))

        self.assertEqual("1,2,A", convert.join_list(",", ["1", "2", "A"]))

        self.assertEqual("", convert.join_list(",", []))

        self.assertEqual("a,B", convert.join_list(",", ("a", "B")))
Пример #5
0
def _places(client, url_part, query=None, location=None, radius=None,
            keyword=None, language=None, min_price=0, max_price=4, name=None,
            open_now=False, rank_by=None, type=None, page_token=None):
    """
    Internal handler for ``places``, ``places_nearby``, and ``places_radar``.
    See each method's docs for arg details.
    """

    params = {"minprice": min_price, "maxprice": max_price}

    if query:
        params["query"] = query
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if keyword:
        params["keyword"] = keyword
    if language:
        params["language"] = language
    if name:
        params["name"] = convert.join_list(" ", name)
    if open_now:
        params["opennow"] = "true"
    if rank_by:
        params["rankby"] = rank_by
    if type:
        params["type"] = type
    if page_token:
        params["pagetoken"] = page_token

    url = "/maps/api/place/%ssearch/json" % url_part
    return client._get(url, params)
Пример #6
0
def snapped_speed_limits(client, path):
    """Returns the posted speed limit (in km/h) for given road segments.

    The provided points will first be snapped to the most likely roads the
    vehicle was traveling along.

    :param path: The path of points to be snapped. A list of (or single)
            latitude/longitude tuples.
    :type path: list or tuple

    :rtype: a dict with both a list of speed limits and a list of the snapped
            points.
    """

    if type(path) is tuple:
        path = [path]

    path = convert.join_list("|",
            [convert.latlng(k) for k in convert.as_list(path)])

    params = {
        "path": path
    }

    return client._get("/v1/speedLimits", params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract)
def find_place(client, input, input_type, fields=None, location_bias=None,
                language=None):
    """
    A Find Place request takes a text input, and returns a place.
    The text input can be any kind of Places data, for example,
    a name, address, or phone number.

    :param input: The text input specifying which place to search for (for
                  example, a name, address, or phone number).
    :type input: string

    :param input_type: The type of input. This can be one of either 'textquery'
                  or 'phonenumber'.
    :type input_type: string

    :param fields: The fields specifying the types of place data to return,
                   separated by a comma. For full details see:
                   https://developers.google.com/places/web-service/search#FindPlaceRequests
    :type input: list

    :param location_bias: Prefer results in a specified area, by specifying
                          either a radius plus lat/lng, or two lat/lng pairs
                          representing the points of a rectangle. See:
                          https://developers.google.com/places/web-service/search#FindPlaceRequests
    :type location_bias: string

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

    :rtype: result dict with the following keys:
            status: status code
            candidates: list of places
    """
    params = {"input": input, "inputtype": input_type}

    if input_type != "textquery" and input_type != "phonenumber":
        raise ValueError("Valid values for the `input_type` param for "
                         "`find_place` are 'textquery' or 'phonenumber', "
                         "the given value is invalid: '%s'" % input_type)

    if fields:
        invalid_fields = set(fields) - PLACES_FIND_FIELDS
        if invalid_fields:
            raise ValueError("Valid values for the `fields` param for "
                             "`find_place` are '%s', these given field(s) "
                             "are invalid: '%s'" % (
                                "', '".join(PLACES_FIND_FIELDS),
                                "', '".join(invalid_fields)))
        params["fields"] = convert.join_list(",", fields)

    if location_bias:
        valid = ["ipbias", "point", "circle", "rectangle"]
        if location_bias.split(":")[0] not in valid:
            raise ValueError("location_bias should be prefixed with one of: %s"
                             % valid)
        params["locationbias"] = location_bias
    if language:
        params["language"] = language

    return client._request("/maps/api/place/findplacefromtext/json", params)
Пример #8
0
def elevation_along_path(client, path, samples):
    """
    Provides elevation data sampled along a path on the surface of the earth.

    :param path: A encoded polyline string, or a list of
            latitude/longitude tuples from which you wish to calculate
            elevation data.
    :type path: str or list

    :param samples: The number of sample points along a path for which to
            return elevation data.
    :type samples: int

    :rtype: list of elevation data responses
    """

    if type(path) is str:
        path = "enc:%s" % path
    else:
        path = convert.join_list(
            "|", [convert.latlng(k) for k in convert.as_list(path)])

    params = {"path": path, "samples": samples}

    return client._get("/maps/api/elevation/json", params)["results"]
Пример #9
0
def elevation_along_path(client, path, samples):
    """
    Provides elevation data sampled along a path on the surface of the earth.

    :param path: A encoded polyline string, or a list of
            latitude/longitude tuples from which you wish to calculate
            elevation data.
    :type path: str or list

    :param samples: The number of sample points along a path for which to
            return elevation data.
    :type samples: int

    :rtype: list of elevation data responses
    """

    if type(path) is str:
        path = "enc:%s" % path
    else:
        path = convert.join_list("|",
                [convert.latlng(k) for k in convert.as_list(path)])

    params = {
        "path": path,
        "samples": samples
    }

    return client._get("/maps/api/elevation/json", params)["results"]
def find_place(client, input, input_type, fields=None, location_bias=None,
                language=None):
    """
    A Find Place request takes a text input, and returns a place.
    The text input can be any kind of Places data, for example,
    a name, address, or phone number.

    :param input: The text input specifying which place to search for (for
                  example, a name, address, or phone number).
    :type input: string

    :param input_type: The type of input. This can be one of either 'textquery'
                  or 'phonenumber'.
    :type input_type: string

    :param fields: The fields specifying the types of place data to return,
                   separated by a comma. For full details see:
                   https://developers.google.com/places/web-service/search#FindPlaceRequests
    :type input: list

    :param location_bias: Prefer results in a specified area, by specifying
                          either a radius plus lat/lng, or two lat/lng pairs
                          representing the points of a rectangle. See:
                          https://developers.google.com/places/web-service/search#FindPlaceRequests
    :type location_bias: string

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

    :rtype: result dict with the following keys:
            status: status code
            candidates: list of places
    """
    params = {"input": input, "inputtype": input_type}

    if input_type != "textquery" and input_type != "phonenumber":
        raise ValueError("Valid values for the `input_type` param for "
                         "`find_place` are 'textquery' or 'phonenumber', "
                         "the given value is invalid: '%s'" % input_type)

    if fields:
        invalid_fields = set(fields) - PLACES_FIND_FIELDS
        if invalid_fields:
            raise ValueError("Valid values for the `fields` param for "
                             "`find_place` are '%s', these given field(s) "
                             "are invalid: '%s'" % (
                                "', '".join(PLACES_FIND_FIELDS),
                                "', '".join(invalid_fields)))
        params["fields"] = convert.join_list(",", fields)

    if location_bias:
        valid = ["ipbias", "point", "circle", "rectangle"]
        if location_bias.split(":")[0] not in valid:
            raise ValueError("location_bias should be prefixed with one of: %s"
                             % valid)
        params["locationbias"] = location_bias
    if language:
        params["language"] = language

    return client._request("/maps/api/place/findplacefromtext/json", params)
Пример #11
0
def _places(client, url_part, query=None, location=None, radius=None,
            keyword=None, language=None, min_price=0, max_price=4, name=None,
            open_now=False, rank_by=None, type=None, region=None, page_token=None):
    """
    Internal handler for ``places``, ``places_nearby``, and ``places_radar``.
    See each method's docs for arg details.
    """

    params = {"minprice": min_price, "maxprice": max_price}

    if query:
        params["query"] = query
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if keyword:
        params["keyword"] = keyword
    if language:
        params["language"] = language
    if name:
        params["name"] = convert.join_list(" ", name)
    if open_now:
        params["opennow"] = "true"
    if rank_by:
        params["rankby"] = rank_by
    if type:
        params["type"] = type
    if region:
        params["region"] = region
    if page_token:
        params["pagetoken"] = page_token

    url = "/maps/api/place/%ssearch/json" % url_part
    return client._request(url, params)
Пример #12
0
Файл: roads.py Проект: th0/test2
def snapped_speed_limits(client, path):
    """Returns the posted speed limit (in km/h) for given road segments.

    The provided points will first be snapped to the most likely roads the
    vehicle was traveling along.

    :param path: The path of points to be snapped. A list of (or single)
            latitude/longitude tuples.
    :type path: list or tuple

    :rtype: a dict with both a list of speed limits and a list of the snapped
            points.
    """

    if type(path) is tuple:
        path = [path]

    path = convert.join_list(
        "|", [convert.latlng(k) for k in convert.as_list(path)])

    params = {"path": path}

    return client._get("/v1/speedLimits",
                       params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract)
Пример #13
0
def distance_matrix(client,
                    origins,
                    destinations,
                    mode=None,
                    language=None,
                    avoid=None,
                    units=None,
                    departure_time=None,
                    arrival_time=None,
                    transit_mode=None,
                    transit_routing_preference=None,
                    traffic_model=None,
                    region=None):
    params = {
        "origins": convert.location_list(origins),
        "destinations": convert.location_list(destinations)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if language:
        params["language"] = language

    if avoid:
        if avoid not in ["tolls", "highways", "ferries"]:
            raise ValueError("Invalid route restriction.")
        params["avoid"] = avoid

    if units:
        params["units"] = units

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    if region:
        params["region"] = region
    #print(client._request("/maps/api/distancematrix/json", params))
    return client._request("/maps/api/distancematrix/json", params)
Пример #14
0
    def __str__(self):
        """Converts a list of parameters to the format expected by
        the Google Maps server.

        :rtype: str

        """
        return convert.join_list('|', self.params)
Пример #15
0
def _convert_path(waypoints):
    # Handle the single-tuple case
    if type(waypoints) is tuple:
        waypoints = [waypoints]
    else:
        waypoints = as_list(waypoints)

    return convert.join_list("|",
            [(k if convert.is_string(k) else convert.latlng(k))
                for k in waypoints])
Пример #16
0
def _convert_path(waypoints):
    # Handle the single-tuple case
    if type(waypoints) is tuple:
        waypoints = [waypoints]
    else:
        waypoints = as_list(waypoints)

    return convert.join_list(
        "|", [(k if convert.is_string(k) else convert.latlng(k))
              for k in waypoints])
Пример #17
0
async def reverse_geocode(client, latlng, result_type=None, location_type=None,
                          language=None):

    if convert.is_string(latlng) and ',' not in latlng:
        params = {'place_id': latlng}
    else:
        params = {'latlng': convert.latlng(latlng)}

    if result_type:
        params['result_type'] = convert.join_list('|', result_type)

    if location_type:
        params['location_type'] = convert.join_list('|', location_type)

    if language:
        params['language'] = language

    result = await client._request('/maps/api/geocode/json', params)
    return result.get('results', [])
def reverse_geocode(client, latlng, result_type=None, location_type=None,
                    language=None):
    """
    Reverse geocoding is the process of converting geographic coordinates into a
    human-readable address.

    :param latlng: The latitude/longitude value or place_id for which you wish
        to obtain the closest, human-readable address.
    :type latlng: string, dict, list, or tuple

    :param result_type: One or more address types to restrict results to.
    :type result_type: string or list of strings

    :param location_type: One or more location types to restrict results to.
    :type location_type: list of strings

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

    :rtype: list of reverse geocoding results.
    """

    # Check if latlng param is a place_id string.
    #  place_id strings do not contain commas; latlng strings do.
    if convert.is_string(latlng) and ',' not in latlng:
        params = {"place_id": latlng}
    else:
        params = {"latlng": convert.latlng(latlng)}

    if result_type:
        params["result_type"] = convert.join_list("|", result_type)

    if location_type:
        params["location_type"] = convert.join_list("|", location_type)

    if language:
        params["language"] = language

    return client._request("/maps/api/geocode/json", params).get("results", [])
Пример #19
0
def place(client, place_id, session_token=None, fields=None, language=None):
    """
    Comprehensive details for an individual place.

    :param place_id: A textual identifier that uniquely identifies a place,
        returned from a Places search.
    :type place_id: string

    :param session_token: A random string which identifies an autocomplete
                          session for billing purposes.
    :type session_token: string

    :param fields: The fields specifying the types of place data to return,
                   separated by a comma. For full details see:
                   https://cloud.google.com/maps-platform/user-guide/product-changes/#places
    :type input: list

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

    :rtype: result dict with the following keys:
        result: dict containing place details
        html_attributions: set of attributions which must be displayed
    """
    params = {"placeid": place_id}

    if fields:
        deprecated_fields = set(fields) & DEPRECATED_FIELDS
        if deprecated_fields:
            warnings.warn(
                DEPRECATED_FIELDS_MESSAGE % str(list(deprecated_fields)),
                DeprecationWarning,
            )

        invalid_fields = set(fields) - PLACES_DETAIL_FIELDS
        if invalid_fields:
            raise ValueError(
                "Valid values for the `fields` param for "
                "`place` are '%s', these given field(s) "
                "are invalid: '%s'"
                % ("', '".join(PLACES_DETAIL_FIELDS), "', '".join(invalid_fields))
            )
        params["fields"] = convert.join_list(",", fields)

    if language:
        params["language"] = language
    if session_token:
        params["sessiontoken"] = session_token

    return client._request("/maps/api/place/details/json", params)
Пример #20
0
def reverse_geocode(client,
                    latlng,
                    result_type=None,
                    location_type=None,
                    language=None):

    # Check if latlng param is a place_id string.
    #  place_id strings do not contain commas; latlng strings do.
    if convert.is_string(latlng) and ',' not in latlng:
        params = {"place_id": latlng}
    else:
        params = {"latlng": convert.latlng(latlng)}

    if result_type:
        params["result_type"] = convert.join_list("|", result_type)

    if location_type:
        params["location_type"] = convert.join_list("|", location_type)

    if language:
        params["language"] = language

    return client._request("/maps/api/geocode/json", params).get("results", [])
def place(client, place_id, session_token=None, fields=None, language=None):
    """
    Comprehensive details for an individual place.

    :param place_id: A textual identifier that uniquely identifies a place,
        returned from a Places search.
    :type place_id: string

    :param session_token: A random string which identifies an autocomplete
                          session for billing purposes.
    :type session_token: string

    :param fields: The fields specifying the types of place data to return,
                   separated by a comma. For full details see:
                   https://cloud.google.com/maps-platform/user-guide/product-changes/#places
    :type input: list

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

    :rtype: result dict with the following keys:
        result: dict containing place details
        html_attributions: set of attributions which must be displayed
    """
    params = {"placeid": place_id}

    if fields:
        invalid_fields = set(fields) - PLACES_DETAIL_FIELDS
        if invalid_fields:
            raise ValueError("Valid values for the `fields` param for "
                             "`place` are '%s', these given field(s) "
                             "are invalid: '%s'" % (
                                "', '".join(PLACES_DETAIL_FIELDS),
                                "', '".join(invalid_fields)))
        params["fields"] = convert.join_list(",", fields)

    if language:
        params["language"] = language
    if session_token:
        params["sessiontoken"] = session_token

    return client._request("/maps/api/place/details/json", params)
Пример #22
0
def elevation(client, locations):
    """
    Provides elevation data for locations provided on the surface of the
    earth, including depth locations on the ocean floor (which return negative
    values)

    :param locations: A single latitude/longitude tuple or dict, or a list of
            latitude/longitude tuples or dicts from which you wish to calculate
            elevation data.
    :type locations: list or tuple

    :rtype: list of elevation data responses
    """
    params = {}
    if type(locations) is tuple:
        locations = [locations]

    params["locations"] = convert.join_list(
        "|", [convert.latlng(k) for k in convert.as_list(locations)])

    return client._get("/maps/api/elevation/json", params)["results"]
Пример #23
0
def elevation(client, locations):
    """
    Provides elevation data for locations provided on the surface of the
    earth, including depth locations on the ocean floor (which return negative
    values)

    :param locations: A single latitude/longitude tuple or dict, or a list of
            latitude/longitude tuples or dicts from which you wish to calculate
            elevation data.
    :type locations: list or tuple

    :rtype: list of elevation data responses
    """
    params = {}
    if type(locations) is tuple:
        locations = [locations]

    params["locations"] = convert.join_list("|",
            [convert.latlng(k) for k in convert.as_list(locations)])

    return client._get("/maps/api/elevation/json", params)["results"]
Пример #24
0
def snap_to_roads(client, path, interpolate=False):
    """Snaps a path to the most likely roads travelled.

    Takes up to 100 GPS points collected along a route, and returns a similar
    set of data with the points snapped to the most likely roads the vehicle
    was traveling along.

    :param path: The path to be snapped. A list of latitude/longitude tuples.
    :type path: list

    :param interpolate: Whether to interpolate a path to include all points
            forming the full road-geometry. When true, additional interpolated
            points will also be returned, resulting in a path that smoothly
            follows the geometry of the road, even around corners and through
            tunnels.  Interpolated paths may contain more points than the
            original path.
    :type interpolate: bool

    :rtype: A list of snapped points.
    """

    if type(path) is tuple:
        path = [path]

    path = convert.join_list("|",
            [convert.latlng(k) for k in convert.as_list(path)])

    params = {
        "path": path
    }

    if interpolate:
        params["interpolate"] = "true"

    return client._get("/v1/snapToRoads", params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract)["snappedPoints"]
Пример #25
0
Файл: roads.py Проект: th0/test2
def snap_to_roads(client, path, interpolate=False):
    """Snaps a path to the most likely roads travelled.

    Takes up to 100 GPS points collected along a route, and returns a similar
    set of data with the points snapped to the most likely roads the vehicle
    was traveling along.

    :param path: The path to be snapped. A list of latitude/longitude tuples.
    :type path: list

    :param interpolate: Whether to interpolate a path to include all points
            forming the full road-geometry. When true, additional interpolated
            points will also be returned, resulting in a path that smoothly
            follows the geometry of the road, even around corners and through
            tunnels.  Interpolated paths may contain more points than the
            original path.
    :type interpolate: bool

    :rtype: A list of snapped points.
    """

    if type(path) is tuple:
        path = [path]

    path = convert.join_list(
        "|", [convert.latlng(k) for k in convert.as_list(path)])

    params = {"path": path}

    if interpolate:
        params["interpolate"] = "true"

    return client._get("/v1/snapToRoads",
                       params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract)["snappedPoints"]
def distance_matrix(client, origins, destinations,
                    mode=None, language=None, avoid=None, units=None,
                    departure_time=None, arrival_time=None, transit_mode=None,
                    transit_routing_preference=None, traffic_model=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param origins: One or more locations and/or latitude/longitude values,
        from which to calculate distance and time. If you pass an address as
        a string, the service will geocode the string and convert it to a
        latitude/longitude coordinate to calculate directions.
    :type origins: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param destinations: One or more addresses and/or lat/lng values, to
        which to calculate distance and time. If you pass an address as a
        string, the service will geocode the string and convert it to a
        latitude/longitude coordinate to calculate directions.
    :type destinations: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param mode: Specifies the mode of transport to use when calculating
        directions. Valid values are "driving", "walking", "transit" or
        "bicycling".
    :type mode: string

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

    :param avoid: Indicates that the calculated route(s) should avoid the
        indicated features. Valid values are "tolls", "highways" or "ferries".
    :type avoid: string

    :param units: Specifies the unit system to use when displaying results.
        Valid values are "metric" or "imperial".
    :type units: string

    :param departure_time: Specifies the desired time of departure.
    :type departure_time: int or datetime.datetime

    :param arrival_time: Specifies the desired time of arrival for transit
        directions. Note: you can't specify both departure_time and
        arrival_time.
    :type arrival_time: int or datetime.datetime

    :param transit_mode: Specifies one or more preferred modes of transit.
        This parameter may only be specified for requests where the mode is
        transit. Valid values are "bus", "subway", "train", "tram", "rail".
        "rail" is equivalent to ["train", "tram", "subway"].
    :type transit_mode: string or list of strings

    :param transit_routing_preference: Specifies preferences for transit
        requests. Valid values are "less_walking" or "fewer_transfers".
    :type transit_routing_preference: string

    :param traffic_model: Specifies the predictive travel time model to use.
        Valid values are "best_guess" or "optimistic" or "pessimistic".
        The traffic_model parameter may only be specified for requests where
        the travel mode is driving, and where the request includes a
        departure_time.

    :rtype: matrix of distances. Results are returned in rows, each row
        containing one origin paired with each destination.
    """

    params = {
        "origins": convert.location_list(origins),
        "destinations": convert.location_list(destinations)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if language:
        params["language"] = language

    if avoid:
        if avoid not in ["tolls", "highways", "ferries"]:
            raise ValueError("Invalid route restriction.")
        params["avoid"] = avoid

    if units:
        params["units"] = units

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    return client._request("/maps/api/distancematrix/json", params)
Пример #27
0
def distance_matrix(client, origins, destinations,
                    mode=None, language=None, avoid=None, units=None,
                    departure_time=None, arrival_time=None, transit_mode=None,
                    transit_routing_preference=None, traffic_model=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param origins: One or more locations and/or latitude/longitude values,
        from which to calculate distance and time. If you pass an address as
        a string, the service will geocode the string and convert it to a
        latitude/longitude coordinate to calculate directions.
    :type origins: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param destinations: One or more addresses and/or lat/lng values, to
        which to calculate distance and time. If you pass an address as a
        string, the service will geocode the string and convert it to a
        latitude/longitude coordinate to calculate directions.
    :type destinations: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param mode: Specifies the mode of transport to use when calculating
        directions. Valid values are "driving", "walking", "transit" or
        "bicycling".
    :type mode: string

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

    :param avoid: Indicates that the calculated route(s) should avoid the
        indicated features. Valid values are "tolls", "highways" or "ferries".
    :type avoid: string

    :param units: Specifies the unit system to use when displaying results.
        Valid values are "metric" or "imperial".
    :type units: string

    :param departure_time: Specifies the desired time of departure.
    :type departure_time: int or datetime.datetime

    :param arrival_time: Specifies the desired time of arrival for transit
        directions. Note: you can't specify both departure_time and
        arrival_time.
    :type arrival_time: int or datetime.datetime

    :param transit_mode: Specifies one or more preferred modes of transit.
        This parameter may only be specified for requests where the mode is
        transit. Valid values are "bus", "subway", "train", "tram", "rail".
        "rail" is equivalent to ["train", "tram", "subway"].
    :type transit_mode: string or list of strings

    :param transit_routing_preference: Specifies preferences for transit
        requests. Valid values are "less_walking" or "fewer_transfers".
    :type transit_routing_preference: string

    :param traffic_model: Specifies the predictive travel time model to use.
        Valid values are "best_guess" or "optimistic" or "pessimistic".
        The traffic_model parameter may only be specified for requests where
        the travel mode is driving, and where the request includes a
        departure_time.

    :rtype: matrix of distances. Results are returned in rows, each row
        containing one origin paired with each destination.
    """

    params = {
        "origins": convert.location_list(origins),
        "destinations": convert.location_list(destinations)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if language:
        params["language"] = language

    if avoid:
        if avoid not in ["tolls", "highways", "ferries"]:
            raise ValueError("Invalid route restriction.")
        params["avoid"] = avoid

    if units:
        params["units"] = units

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    return client._get("/maps/api/distancematrix/json", params)
def directions(client, origin, destination,
               mode=None, waypoints=None, alternatives=False, avoid=None,
               language=None, units=None, region=None, departure_time=None,
               arrival_time=None, optimize_waypoints=False, transit_mode=None,
               transit_routing_preference=None, traffic_model=None):
    """Get directions between an origin point and a destination point.

    :param origin: The address or latitude/longitude value from which you wish
        to calculate directions.
    :type origin: string, dict, list, or tuple

    :param destination: The address or latitude/longitude value from which
        you wish to calculate directions.
    :type destination: string, dict, list, or tuple

    :param mode: Specifies the mode of transport to use when calculating
        directions. One of "driving", "walking", "bicycling" or "transit"
    :type mode: string

    :param waypoints: Specifies an array of waypoints. Waypoints alter a
        route by routing it through the specified location(s).
    :type waypoints: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param alternatives: If True, more than one route may be returned in the
        response.
    :type alternatives: bool

    :param avoid: Indicates that the calculated route(s) should avoid the
        indicated features.
    :type avoid: list or string

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

    :param units: Specifies the unit system to use when displaying results.
        "metric" or "imperial"
    :type units: string

    :param region: The region code, specified as a ccTLD ("top-level domain"
        two-character value.
    :type region: string

    :param departure_time: Specifies the desired time of departure.
    :type departure_time: int or datetime.datetime

    :param arrival_time: Specifies the desired time of arrival for transit
        directions. Note: you can't specify both departure_time and
        arrival_time.
    :type arrival_time: int or datetime.datetime

    :param optimize_waypoints: Optimize the provided route by rearranging the
        waypoints in a more efficient order.
    :type optimize_waypoints: bool

    :param transit_mode: Specifies one or more preferred modes of transit.
        This parameter may only be specified for requests where the mode is
        transit. Valid values are "bus", "subway", "train", "tram", "rail".
        "rail" is equivalent to ["train", "tram", "subway"].
    :type transit_mode: string or list of strings

    :param transit_routing_preference: Specifies preferences for transit
        requests. Valid values are "less_walking" or "fewer_transfers"
    :type transit_routing_preference: string

    :param traffic_model: Specifies the predictive travel time model to use.
        Valid values are "best_guess" or "optimistic" or "pessimistic".
        The traffic_model parameter may only be specified for requests where
        the travel mode is driving, and where the request includes a
        departure_time.
    :type units: string

    :rtype: list of routes
    """

    params = {
        "origin": convert.latlng(origin),
        "destination": convert.latlng(destination)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if waypoints:
        waypoints = convert.location_list(waypoints)
        if optimize_waypoints:
            waypoints = "optimize:true|" + waypoints
        params["waypoints"] = waypoints

    if alternatives:
        params["alternatives"] = "true"

    if avoid:
        params["avoid"] = convert.join_list("|", avoid)

    if language:
        params["language"] = language

    if units:
        params["units"] = units

    if region:
        params["region"] = region

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    return client._get("/maps/api/directions/json", params)["routes"]
Пример #29
0
def directions(origin,
               destination,
               mode=None,
               waypoints=None,
               alternatives=False,
               avoid=None,
               language=None,
               units=None,
               region=None,
               departure_time=None,
               arrival_time=None,
               optimize_waypoints=False,
               transit_mode=None,
               transit_routing_preference=None,
               traffic_model=None):
    # also directly from GitHub
    params = {
        "origin": convert.latlng(getlatlong(origin)),
        "destination": convert.latlng(getlatlong(destination))
    }

    if mode:
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if waypoints:
        waypoints = convert.location_list(waypoints)
        if optimize_waypoints:
            waypoints = "optimize:true|" + waypoints
        params["waypoints"] = waypoints

    if alternatives:
        params["alternatives"] = "true"

    if avoid:
        params["avoid"] = convert.join_list("|", avoid)

    if language:
        params["language"] = language

    if units:
        params["units"] = units

    if region:
        params["region"] = region

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    return gmaps._request("/maps/api/directions/json",
                          params).get("routes", [])[0]["legs"][0]
Пример #30
0
def directions(client, origin, destination,
               mode=None, waypoints=None, alternatives=False, avoid=None,
               language=None, units=None, region=None, departure_time=None,
               arrival_time=None, optimize_waypoints=False, transit_mode=None,
               transit_routing_preference=None, traffic_model=None):
    """Get directions between an origin point and a destination point.

    :param origin: The address or latitude/longitude value from which you wish
        to calculate directions.
    :type origin: string, dict, list, or tuple

    :param destination: The address or latitude/longitude value from which
        you wish to calculate directions.
    :type destination: string, dict, list, or tuple

    :param mode: Specifies the mode of transport to use when calculating
        directions. One of "driving", "walking", "bicycling" or "transit"
    :type mode: string

    :param waypoints: Specifies an array of waypoints. Waypoints alter a
        route by routing it through the specified location(s).
    :type waypoints: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param alternatives: If True, more than one route may be returned in the
        response.
    :type alternatives: bool

    :param avoid: Indicates that the calculated route(s) should avoid the
        indicated features.
    :type avoid: list or string

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

    :param units: Specifies the unit system to use when displaying results.
        "metric" or "imperial"
    :type units: string

    :param region: The region code, specified as a ccTLD ("top-level domain"
        two-character value.
    :type region: string

    :param departure_time: Specifies the desired time of departure.
    :type departure_time: int or datetime.datetime

    :param arrival_time: Specifies the desired time of arrival for transit
        directions. Note: you can't specify both departure_time and
        arrival_time.
    :type arrival_time: int or datetime.datetime

    :param optimize_waypoints: Optimize the provided route by rearranging the
        waypoints in a more efficient order.
    :type optimize_waypoints: bool

    :param transit_mode: Specifies one or more preferred modes of transit.
        This parameter may only be specified for requests where the mode is
        transit. Valid values are "bus", "subway", "train", "tram", "rail".
        "rail" is equivalent to ["train", "tram", "subway"].
    :type transit_mode: string or list of strings

    :param transit_routing_preference: Specifies preferences for transit
        requests. Valid values are "less_walking" or "fewer_transfers"
    :type transit_routing_preference: string

    :param traffic_model: Specifies the predictive travel time model to use.
        Valid values are "best_guess" or "optimistic" or "pessimistic".
        The traffic_model parameter may only be specified for requests where
        the travel mode is driving, and where the request includes a
        departure_time.
    :type units: string

    :rtype: list of routes
    """

    params = {
        "origin": convert.latlng(origin),
        "destination": convert.latlng(destination)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if waypoints:
        waypoints = convert.location_list(waypoints)
        if optimize_waypoints:
            waypoints = "optimize:true|" + waypoints
        params["waypoints"] = waypoints

    if alternatives:
        params["alternatives"] = "true"

    if avoid:
        params["avoid"] = convert.join_list("|", avoid)

    if language:
        params["language"] = language

    if units:
        params["units"] = units

    if region:
        params["region"] = region

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    return client._request("/maps/api/directions/json", params).get("routes", [])
Пример #31
0
async def directions(client, origin, destination,
                     mode=None, waypoints=None, alternatives=False,
                     avoid=None, language=None, units=None, region=None,
                     departure_time=None, arrival_time=None,
                     optimize_waypoints=False,
                     transit_routing_preference=None,
                     transit_mode=None,
                     traffic_model=None):

    params = {
        'origin': convert.latlng(origin),
        'destination': convert.latlng(destination)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ['driving', 'walking', 'bicycling', 'transit']:
            raise ValueError('Invalid travel mode.')
        params['mode'] = mode

    if waypoints:
        waypoints = convert.location_list(waypoints)
        if optimize_waypoints:
            waypoints = 'optimize:true|' + waypoints
        params['waypoints'] = waypoints

    if alternatives:
        params['alternatives'] = 'true'

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

    if language:
        params['language'] = language

    if units:
        params['units'] = units

    if region:
        params['region'] = region

    if departure_time:
        params['departure_time'] = convert.time(departure_time)

    if arrival_time:
        params['arrival_time'] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError('Should not specify both departure_time and'
                         'arrival_time.')

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

    if transit_routing_preference:
        params['transit_routing_preference'] = transit_routing_preference

    if traffic_model:
        params['traffic_model'] = traffic_model

    result = await client._request('/maps/api/directions/json', params)
    return result.get('routes', [])
Пример #32
0
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if waypoints:
        waypoints = convert.location_list(waypoints)
        if optimize_waypoints:
            waypoints = "optimize:true|" + waypoints
        params["waypoints"] = waypoints

    if alternatives:
        params["alternatives"] = "true"

    if avoid:
        params["avoid"] = convert.join_list("|", avoid)

    if language:
        params["language"] = language

    if units:
        params["units"] = units

    if region:
        params["region"] = region

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)
def distance_between(origins,
                     destinations,
                     mode="driving",
                     language=None,
                     avoid=None,
                     units=None,
                     departure_time=None,
                     arrival_time=None,
                     transit_mode=None,
                     transit_routing_preference=None,
                     traffic_model=None,
                     region=None):

    params = {
        "origins": convert.location_list(origins),
        "destinations": convert.location_list(destinations)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if language:
        params["language"] = language

    if avoid:
        if avoid not in ["tolls", "highways", "ferries"]:
            raise ValueError("Invalid route restriction.")
        params["avoid"] = avoid

    if units:
        params["units"] = units

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    if region:
        params["region"] = region
    client = googlemaps.Client(key='AIzaSyBWiIuZnjTM3pZcpr6e8xnCnupC2nKwJ_4')

    response = client._request("/maps/api/distancematrix/json", params)
    if (response.get("status") != 'OK'):
        print(response)
        return response
    else:
        rows = response.get("rows")
        elements = rows[0].get("elements")
        text_distance = elements[0].get("distance").get("text")
        duration_text = elements[0].get("duration").get("text")
        valuableData = f"The distance between {origins} and {destinations} is {text_distance} and it will take you about {duration_text} to reach {destinations} by {mode}"
        print(valuableData)
        return valuableData


#print(distance_between(  "96 symonds street auckland 1010", "mt albert primary auckland"))