Example #1
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']
 def directions(self, client, origin, destination, waypoints):
     params = {
         "origin": convert.latlng(origin),
         "destination": convert.latlng(destination)
     }
     waypoints = convert.location_list(waypoints)
     optimize_waypoints = True
     if optimize_waypoints:
         waypoints = "optimize:true|" + waypoints
     params["waypoints"] = waypoints
     return client._get("/maps/api/directions/json",
                        params)["routes"][0]["waypoint_order"]
Example #3
0
    def test_location_list(self):
        expected = "1,2|1,2"
        ll = [{"lat": 1, "lng": 2}, {"lat": 1, "lng": 2}]
        self.assertEqual(expected, convert.location_list(ll))

        ll = [[1, 2], [1, 2]]
        self.assertEqual(expected, convert.location_list(ll))

        ll = [(1, 2), [1, 2]]
        self.assertEqual(expected, convert.location_list(ll))

        self.assertEqual(expected, convert.location_list(expected))

        with self.assertRaises(TypeError):
            convert.latlng(1)
Example #4
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 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 _autocomplete(client, url_part, input_text, session_token=None,
                  offset=None, location=None, radius=None, language=None,
                  types=None, components=None, strict_bounds=False):
    """
    Internal handler for ``autocomplete`` and ``autocomplete_query``.
    See each method's docs for arg details.
    """

    params = {"input": input_text}

    if session_token:
        params["sessiontoken"] = session_token
    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if types:
        params["types"] = types
    if components:
        if len(components) != 1 or list(components.keys())[0] != "country":
            raise ValueError("Only country components are supported")
        params["components"] = convert.components(components)
    if strict_bounds:
        params["strictbounds"] = "true"

    url = "/maps/api/place/%sautocomplete/json" % url_part
    return client._request(url, params).get("predictions", [])
Example #7
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)
Example #8
0
def _autocomplete(client,
                  url_part,
                  input_text,
                  offset=None,
                  location=None,
                  radius=None,
                  language=None,
                  type=None,
                  components=None):
    """
    Internal handler for ``autocomplete`` and ``autocomplete_query``.
    See each method's docs for arg details.
    """

    params = {"input": input_text}

    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if type:
        params["type"] = type
    if components:
        params["components"] = convert.components(components)

    url = "/maps/api/place/%sautocomplete/json" % url_part
    return client._get(url, params)["predictions"]
Example #9
0
def _autocomplete(client, url_part, input_text, offset=None, location=None,
                  radius=None, language=None, types=None, components=None,
                  strict_bounds=False):
    """
    Internal handler for ``autocomplete`` and ``autocomplete_query``.
    See each method's docs for arg details.
    """

    params = {"input": input_text}

    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if types:
        params["types"] = types
    if components:
        if len(components) != 1 or list(components.keys())[0] != "country":
            raise ValueError("Only country components are supported")
        params["components"] = convert.components(components)
    if strict_bounds:
        params["strictbounds"] = "true"

    url = "/maps/api/place/%sautocomplete/json" % url_part
    return client._request(url, params).get("predictions", [])
Example #10
0
async def _autocomplete(client,
                        url_part,
                        input_text,
                        offset=None,
                        location=None,
                        radius=None,
                        language=None,
                        types=None,
                        components=None,
                        strict_bounds=False):

    params = {'input': input_text}

    if offset:
        params['offset'] = offset
    if location:
        params['location'] = convert.latlng(location)
    if radius:
        params['radius'] = radius
    if language:
        params['language'] = language
    if types:
        params['types'] = types
    if components:
        params['components'] = convert.components(components)
    if strict_bounds:
        params['strictbounds'] = 'true'

    url = '/maps/api/place/%sautocomplete/json' % url_part
    result = await client._request(url, params)
    return result['predictions']
Example #11
0
def timezone(client, location, timestamp=None, language=None):
    """Get time zone for a location on the earth, as well as that location's
    time offset from UTC.

    :param location: The latitude/longitude value representing the location to
        look up.
    :type location: string, dict, list, or tuple

    :param timestamp: Timestamp specifies the desired time as seconds since
        midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to
        determine whether or not Daylight Savings should be applied. Times
        before 1970 can be expressed as negative values. Optional. Defaults to
        ``datetime.utcnow()``.
    :type timestamp: int or datetime.datetime

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

    :rtype: dict
    """

    params = {
        "location": convert.latlng(location),
        "timestamp": convert.time(timestamp or datetime.utcnow())
    }

    if language:
        params["language"] = language

    return client._request("/maps/api/timezone/json", params)
Example #12
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"]
Example #13
0
File: roads.py Project: 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)
Example #14
0
def timezone(client, location, timestamp=None, language=None):
    """Get time zone for a location on the earth, as well as that location's
    time offset from UTC.

    :param location: The latitude/longitude value representing the location to
        look up.
    :type location: dict or tuple

    :param timestamp: Timestamp specifies the desired time as seconds since
        midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to
        determine whether or not Daylight Savings should be applied. Times
        before 1970 can be expressed as negative values. Optional. Defaults to
        ``datetime.now()``.
    :type timestamp: int or datetime.datetime

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

    :rtype: dict
    """

    location = convert.latlng(location)

    timestamp = convert.time(timestamp or datetime.now())

    params = {
        "location": location,
        "timestamp": timestamp
    }

    if language:
        params["language"] = language

    return client._get( "/maps/api/timezone/json", params)
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", [])
Example #16
0
def json_string(position):
    var_position = {"lng": position['lon']}
    position.update(var_position)
    replaced_value = position.pop('lon', None)
    api_key = "AIzaSyAJfU73lg9Th2JqeujeT1857cpxjXOjYso"
    client = googlemaps.Client(api_key)
    return convert.latlng(position)
Example #17
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 _autocomplete(client, url_part, input_text, offset=None, location=None,
                  radius=None, language=None, types=None, components=None,
                  strict_bounds=False):
    """
    Internal handler for ``autocomplete`` and ``autocomplete_query``.
    See each method's docs for arg details.
    """

    params = {"input": input_text}

    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if types:
        params["types"] = types
    if components:
        params["components"] = convert.components(components)
    if strict_bounds:
        params["strictbounds"] = "true"

    url = "/maps/api/place/%sautocomplete/json" % url_part
    return client._request(url, params).get("predictions", [])
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)
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])
Example #21
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])
Example #22
0
def timezone(location: str, timestamp=None, language=None):
    # taken directly from Google's API example on GitHub
    params = {
        "location": convert.latlng(getlatlong(location)),
        "timestamp": convert.time(timestamp or datetime.utcnow())
    }
    if language:
        params["language"] = language
    ret = gmaps._request("/maps/api/timezone/json", params)
    return (ret["rawOffset"] + ret["dstOffset"]) / 3600
def _autocomplete(client, url_part, input_text, **params):
    """
    Internal handler for ``autocomplete`` and ``autocomplete_query``.
    See each method's docs for arg details.
    """

    params['input'] = input_text

    if 'location' in params:
        params["location"] = convert.latlng(params["location"])
    if 'components' in params:
        params["components"] = convert.components(params["components"])

    url = "/maps/api/place/%sautocomplete/json" % url_part
    return client._request(url, params)["predictions"]
    def test_latlng(self):
        ll = {"lat": 1, "lng": 2}
        self.assertEqual("1.000000,2.000000", convert.latlng(ll))

        ll = [1, 2]
        self.assertEqual("1.000000,2.000000", convert.latlng(ll))

        ll = (1, 2)
        self.assertEqual("1.000000,2.000000", convert.latlng(ll))

        with self.assertRaises(TypeError):
            convert.latlng(1)

        with self.assertRaises(TypeError):
            convert.latlng("test")
Example #25
0
def streetview(client, location, size, heading=None, fov=None):
    params = {
        "location": convert.latlng(location),
        "size": size
    }

    if heading:
        params["heading"] = heading

    if fov:
        params["fov"] = fov

    def extract_body(response):
        if response.status_code != 200:
            raise googlemaps.exceptions.HTTPError(response.status_code)
        return response.content

    return client._request("/maps/api/streetview", params, extract_body=extract_body)
def places_autocomplete(client,
                        input_text,
                        offset=None,
                        location=None,
                        radius=None,
                        language=None):
    """
    Returns Place predictions given a textual search query, such as
    "pizza near New York", and optional geographic bounds.

    :param input_text: The text query on which to search.
    :type input_text: string

    :param offset: The position, in the input term, of the last character
        that the service uses to match predictions. For example, if the input
        is 'Google' and the offset is 3, the service will match on 'Goo'.
    :type offset: int

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

    :param radius: Distance in meters within which to bias results.
    :type radius: number

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

    :rtype: list of predictions
    """

    params = {"input": input_text}

    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language

    response = client._get("/maps/api/place/queryautocomplete/json", params)
    return response["predictions"]
Example #27
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', [])
Example #28
0
    def test_latlng(self):
        expected = "1,2"
        ll = {"lat": 1, "lng": 2}
        self.assertEqual(expected, convert.latlng(ll))

        ll = [1, 2]
        self.assertEqual(expected, convert.latlng(ll))

        ll = (1, 2)
        self.assertEqual(expected, convert.latlng(ll))

        self.assertEqual(expected, convert.latlng(expected))

        with self.assertRaises(TypeError):
            convert.latlng(1)
Example #29
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"]
Example #30
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"]
def places_autocomplete(client, input_text, offset=None, location=None,
                        radius=None, language=None):
    """
    Returns Place predictions given a textual search query, such as
    "pizza near New York", and optional geographic bounds.

    :param input_text: The text query on which to search.
    :type input_text: string

    :param offset: The position, in the input term, of the last character
        that the service uses to match predictions. For example, if the input
        is 'Google' and the offset is 3, the service will match on 'Goo'.
    :type offset: int

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

    :param radius: Distance in meters within which to bias results.
    :type radius: number

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

    :rtype: list of predictions
    """

    params = {"input": input_text}

    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language

    response = client._get("/maps/api/place/queryautocomplete/json", params)
    return response["predictions"]
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", [])
Example #33
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"]
Example #34
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", [])
Example #35
0
File: roads.py Project: 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 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"]
Example #37
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]
Example #38
0
def getCurrentLocation():
    currentLoc = geocoder.ip('me').latlng
    js = {"lat": currentLoc[0], "lng": currentLoc[1]}
    json_dump = json.dumps(js)
    return convert.latlng(json_dump)
Example #39
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", [])
Example #40
0
def _convert_waypoint(waypoint):
    if not convert.is_string(waypoint):
        return convert.latlng(waypoint)

    return waypoint
Example #41
0
def _convert_waypoint(waypoint):
    if not convert.is_string(waypoint):
        return convert.latlng(waypoint)

    return waypoint
def places(client,
           query,
           location=None,
           radius=None,
           language=None,
           min_price=None,
           max_price=None,
           open_now=False,
           types=None,
           page_token=None):
    """
    Places search.

    :param query: The text string on which to search, for example: "restaurant".
    :type query: string

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

    :param radius: Distance in meters within which to bias results.
    :type radius: int

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

    :param min_price: Restricts results to only those places with no less than
        this price level. Valid values are in the range from 0 (most affordable)
        to 4 (most expensive).
    :type min_price: int

    :param max_price: Restricts results to only those places with no greater
        than this price level. Valid values are in the range from 0 (most
        affordable) to 4 (most expensive).
    :type max_price: int

    :param open_now: Return only those places that are open for business at
        the time the query is sent.
    :type open_now: bool

    :param types: Restricts the results to places matching at least one of the
        specified types. The full list of supported types is available here:
        https://developers.google.com/places/supported_types
    :type types: string or list of strings

    :param page_token: Token from a previous search that when provided will
        returns the next page of results for the same search.
    :type page_token: string

    :rtype: result dict with the following keys:
        results: list of places
        html_attributions: set of attributions which must be displayed
        next_page_token: token for retrieving the next page of results
    """
    params = {"query": query}

    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if min_price:
        params["minprice"] = min_price
    if max_price:
        params["maxprice"] = max_price
    if open_now:
        params["opennow"] = "true"
    if page_token:
        params["pagetoken"] = page_token

    return client._get("/maps/api/place/textsearch/json", params)
Example #43
0
def static_map(client,
               size,
               center=None,
               zoom=None,
               scale=None,
               format=None,
               maptype=None,
               language=None,
               region=None,
               markers=None,
               path=None,
               visible=None,
               style=None):
    """
    Downloads a map image from the Maps Static API.

    See https://developers.google.com/maps/documentation/maps-static/intro
    for more info, including more detail for each parameter below.

    :param size: Defines the rectangular dimensions of the map image.
    :type param: int or list

    :param center: Defines the center of the map, equidistant from all edges
        of the map.
    :type center: dict or list or string

    :param zoom: Defines the zoom level of the map, which determines the
        magnification level of the map.
    :type zoom: int

    :param scale: Affects the number of pixels that are returned.
    :type scale: int

    :param format: Defines the format of the resulting image.
    :type format: string

    :param maptype: defines the type of map to construct. There are several
        possible maptype values, including roadmap, satellite, hybrid,
        and terrain.
    :type maptype: string

    :param language: defines the language to use for display of labels on
        map tiles.
    :type language: string

    :param region: defines the appropriate borders to display, based on
        geo-political sensitivities.
    :type region: string

    :param markers: define one or more markers to attach to the image at
        specified locations.
    :type markers: StaticMapMarker

    :param path: defines a single path of two or more connected points to
        overlay on the image at specified locations.
    :type path: StaticMapPath

    :param visible: specifies one or more locations that should remain visible
        on the map, though no markers or other indicators will be displayed.
    :type visible: list of dict

    :param style: defines a custom style to alter the presentation of
        a specific feature (roads, parks, and other features) of the map.
    :type style: list of dict

    :rtype: iterator containing the raw image data, which typically can be
        used to save an image file locally. For example:

        ```
        f = open(local_filename, 'wb')
        for chunk in client.static_map(size=(400, 400),
                                       center=(52.520103, 13.404871),
                                       zoom=15):
            if chunk:
                f.write(chunk)
        f.close()
        ```
    """

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

    if not markers:
        if not (center or zoom is not None):
            raise ValueError("both center and zoom are required"
                             "when markers is not specifed")

    if center:
        params["center"] = convert.latlng(center)

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

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

    if format:
        if format not in MAPS_IMAGE_FORMATS:
            raise ValueError("Invalid image format")
        params['format'] = format

    if maptype:
        if maptype not in MAPS_MAP_TYPES:
            raise ValueError("Invalid maptype")
        params["maptype"] = maptype

    if language:
        params["language"] = language

    if region:
        params["region"] = region

    if markers:
        params["markers"] = markers

    if path:
        params["path"] = path

    if visible:
        params["visible"] = convert.location_list(visible)

    if style:
        params["style"] = convert.components(style)

    response = client._request(
        "/maps/api/staticmap",
        params,
        extract_body=lambda response: response,
        requests_kwargs={"stream": True},
    )
    return response.iter_content()
def places(client, query, location=None, radius=None, language=None,
           min_price=None, max_price=None, open_now=False, types=None,
           page_token=None):
    """
    Places search.

    :param query: The text string on which to search, for example: "restaurant".
    :type query: string

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

    :param radius: Distance in meters within which to bias results.
    :type radius: int

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

    :param min_price: Restricts results to only those places with no less than
        this price level. Valid values are in the range from 0 (most affordable)
        to 4 (most expensive).
    :type min_price: int

    :param max_price: Restricts results to only those places with no greater
        than this price level. Valid values are in the range from 0 (most
        affordable) to 4 (most expensive).
    :type max_price: int

    :param open_now: Return only those places that are open for business at
        the time the query is sent.
    :type open_now: bool

    :param types: Restricts the results to places matching at least one of the
        specified types. The full list of supported types is available here:
        https://developers.google.com/places/supported_types
    :type types: string or list of strings

    :param page_token: Token from a previous search that when provided will
        returns the next page of results for the same search.
    :type page_token: string

    :rtype: result dict with the following keys:
        results: list of places
        html_attributions: set of attributions which must be displayed
        next_page_token: token for retrieving the next page of results
    """
    params = {"query": query}

    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if min_price:
        params["minprice"] = min_price
    if max_price:
        params["maxprice"] = max_price
    if open_now:
        params["opennow"] = "true"
    if page_token:
        params["pagetoken"] = page_token

    return client._get("/maps/api/place/textsearch/json", params)