当前位置: 首页>>代码示例>>Python>>正文


Python googlemaps.Client方法代码示例

本文整理汇总了Python中googlemaps.Client方法的典型用法代码示例。如果您正苦于以下问题:Python googlemaps.Client方法的具体用法?Python googlemaps.Client怎么用?Python googlemaps.Client使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在googlemaps的用法示例。


在下文中一共展示了googlemaps.Client方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_queries_per_second

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_queries_per_second(self):
        # This test assumes that the time to run a mocked query is
        # relatively small, eg a few milliseconds. We define a rate of
        # 3 queries per second, and run double that, which should take at
        # least 1 second but no more than 2.
        queries_per_second = 3
        query_range = range(queries_per_second * 2)
        for _ in query_range:
            responses.add(
                responses.GET,
                "https://maps.googleapis.com/maps/api/geocode/json",
                body='{"status":"OK","results":[]}',
                status=200,
                content_type="application/json",
            )
        client = googlemaps.Client(
            key="AIzaasdf", queries_per_second=queries_per_second
        )
        start = time.time()
        for _ in query_range:
            client.geocode("Sesame St.")
        end = time.time()
        self.assertTrue(start + 1 < end < start + 2) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:25,代码来源:test_client.py

示例2: test_key_sent

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_key_sent(self):
        responses.add(
            responses.GET,
            "https://maps.googleapis.com/maps/api/geocode/json",
            body='{"status":"OK","results":[]}',
            status=200,
            content_type="application/json",
        )

        client = googlemaps.Client(key="AIzaasdf")
        client.geocode("Sesame St.")

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            "https://maps.googleapis.com/maps/api/geocode/json?"
            "key=AIzaasdf&address=Sesame+St.",
            responses.calls[0].request.url,
        ) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:20,代码来源:test_client.py

示例3: test_extra_params

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_extra_params(self):
        responses.add(
            responses.GET,
            "https://maps.googleapis.com/maps/api/geocode/json",
            body='{"status":"OK","results":[]}',
            status=200,
            content_type="application/json",
        )

        client = googlemaps.Client(key="AIzaasdf")
        client.geocode("Sesame St.", extra_params={"foo": "bar"})

        self.assertEqual(1, len(responses.calls))
        self.assertURLEqual(
            "https://maps.googleapis.com/maps/api/geocode/json?"
            "key=AIzaasdf&address=Sesame+St.&foo=bar",
            responses.calls[0].request.url,
        ) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:20,代码来源:test_client.py

示例4: test_url_signed

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_url_signed(self):
        responses.add(
            responses.GET,
            "https://maps.googleapis.com/maps/api/geocode/json",
            body='{"status":"OK","results":[]}',
            status=200,
            content_type="application/json",
        )

        client = googlemaps.Client(client_id="foo", client_secret="a2V5")
        client.geocode("Sesame St.")

        self.assertEqual(1, len(responses.calls))

        # Check ordering of parameters.
        self.assertIn(
            "address=Sesame+St.&client=foo&signature", responses.calls[0].request.url
        )
        self.assertURLEqual(
            "https://maps.googleapis.com/maps/api/geocode/json?"
            "address=Sesame+St.&client=foo&"
            "signature=fxbWUIcNPZSekVOhp2ul9LW5TpY=",
            responses.calls[0].request.url,
        ) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:26,代码来源:test_client.py

示例5: test_custom_extract

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_custom_extract(self):
        def custom_extract(resp):
            return resp.json()

        responses.add(
            responses.GET,
            "https://maps.googleapis.com/bar",
            body='{"error":"errormessage"}',
            status=403,
            content_type="application/json",
        )

        client = googlemaps.Client(key="AIzaasdf")
        b = client._get("/bar", {}, extract_body=custom_extract)
        self.assertEqual(1, len(responses.calls))
        self.assertEqual("errormessage", b["error"]) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:18,代码来源:test_client.py

示例6: test_retry_intermittent

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_retry_intermittent(self):
        class request_callback:
            def __init__(self):
                self.first_req = True

            def __call__(self, req):
                if self.first_req:
                    self.first_req = False
                    return (500, {}, "Internal Server Error.")
                return (200, {}, '{"status":"OK","results":[]}')

        responses.add_callback(
            responses.GET,
            "https://maps.googleapis.com/maps/api/geocode/json",
            content_type="application/json",
            callback=request_callback(),
        )

        client = googlemaps.Client(key="AIzaasdf")
        client.geocode("Sesame St.")

        self.assertEqual(2, len(responses.calls)) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:24,代码来源:test_client.py

示例7: test_auth_url_with_channel

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_auth_url_with_channel(self):
        client = googlemaps.Client(
            key="AIzaasdf", client_id="foo", client_secret="a2V5", channel="MyChannel_1"
        )

        # Check ordering of parameters + signature.
        auth_url = client._generate_auth_url(
            "/test", {"param": "param"}, accepts_clientid=True
        )
        self.assertEqual(
            auth_url,
            "/test?param=param"
            "&channel=MyChannel_1"
            "&client=foo"
            "&signature=OH18GuQto_mEpxj99UimKskvo4k=",
        )

        # Check if added to requests to API with accepts_clientid=False
        auth_url = client._generate_auth_url(
            "/test", {"param": "param"}, accepts_clientid=False
        )
        self.assertEqual(auth_url, "/test?param=param&key=AIzaasdf") 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:24,代码来源:test_client.py

示例8: test_requests_version

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_requests_version(self):
        client_args_timeout = {
            "key": "AIzaasdf",
            "client_id": "foo",
            "client_secret": "a2V5",
            "channel": "MyChannel_1",
            "connect_timeout": 5,
            "read_timeout": 5,
        }
        client_args = client_args_timeout.copy()
        del client_args["connect_timeout"]
        del client_args["read_timeout"]

        requests.__version__ = "2.3.0"
        with self.assertRaises(NotImplementedError):
            googlemaps.Client(**client_args_timeout)
        googlemaps.Client(**client_args)

        requests.__version__ = "2.4.0"
        googlemaps.Client(**client_args_timeout)
        googlemaps.Client(**client_args) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:23,代码来源:test_client.py

示例9: test_experience_id_sample

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_experience_id_sample(self):
        # [START maps_experience_id]
        experience_id = str(uuid.uuid4())

        # instantiate client with experience id
        client = googlemaps.Client(key="AIza-Maps-API-Key", experience_id=experience_id)

        # clear the current experience id
        client.clear_experience_id()

        # set a new experience id
        other_experience_id = str(uuid.uuid4())
        client.set_experience_id(experience_id, other_experience_id)

        # make API request, the client will set the header
        # X-GOOG-MAPS-EXPERIENCE-ID: experience_id,other_experience_id

        # get current experience id
        ids = client.get_experience_id()
        # [END maps_experience_id]

        result = "%s,%s" % (experience_id, other_experience_id)
        self.assertEqual(result, ids) 
开发者ID:googlemaps,项目名称:google-maps-services-python,代码行数:25,代码来源:test_client.py

示例10: from_google

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def from_google(cls, config, search_area):
        """
        Get a bounding box from Google
        """
        try:
            gmaps = googlemaps.Client(key=config.GOOGLE_API_KEY)
            results = gmaps.geocode((search_area))
            bounds = results[0]["geometry"]["bounds"]
            bounding_box = (bounds["southwest"]["lat"],
                            bounds["northeast"]["lat"],
                            bounds["southwest"]["lng"],
                            bounds["northeast"]["lng"],)
            return cls(bounding_box)
        except:
            LOGGER.exception("Exception in BoundingBox_from_google: exiting")
            sys.exit() 
开发者ID:tomslee,项目名称:airbnb-data-collection,代码行数:18,代码来源:reverse_geocode.py

示例11: boot

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def boot(service_container):
    # PoGoApi parameters
    config = service_container.get('config.core')

    if os.path.isfile(os.path.join(os.getcwd(), config['load_library'])):
        config['load_library'] = os.path.join(os.getcwd(), config['load_library'])

    service_container.set_parameter('pogoapi.provider', config['login']['auth_service'])
    service_container.set_parameter('pogoapi.username', config['login']['username'])
    service_container.set_parameter('pogoapi.password', config['login']['password'])
    service_container.set_parameter('pogoapi.shared_lib', config['load_library'])

    service_container.register_singleton('pgoapi', PGoApi())
    service_container.register_singleton('google_maps', googlemaps.Client(key=config["mapping"]["gmapkey"]))

    if config['movement']['path_finder'] in ['google', 'direct']:
        service_container.set_parameter('path_finder', config['movement']['path_finder'] + '_path_finder')
    else:
        raise Exception('You must provide a valid path finder')

    if config['movement']['navigator'] in ['fort', 'waypoint', 'camper']:
        service_container.set_parameter('navigator', config['movement']['navigator'] + '_navigator')
    else:
        raise Exception('You must provide a valid navigator') 
开发者ID:tehp,项目名称:OpenPoGoBot,代码行数:26,代码来源:__init__.py

示例12: test_find_location_with_coordinates_invalid_response

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def test_find_location_with_coordinates_invalid_response():
        config = create_core_test_config()
        api_wrapper = create_mock_api_wrapper(config)
        google_maps = Mock(spec=Client)
        google_maps.elevation = Mock(return_value=None)
        location = Mock()
        location.latitude = 51.5044524
        location.longitude = -0.0752479
        location.altitude = 10.1
        google_maps.geocode = Mock(return_value=location)
        logger = Mock()
        logger.log = Mock(return_value=None)
        mapper = Mapper(config, api_wrapper, google_maps, logger)

        lat, lng, alt = mapper.find_location('51.5044524, -0.0752479')

        assert lat == 51.5044524
        assert lng == -0.0752479
        assert alt == 10.1 
开发者ID:tehp,项目名称:OpenPoGoBot,代码行数:21,代码来源:mapper_test.py

示例13: directions

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def directions(start, end, unsafe=False):

    mapService = GoogleMaps(GOOGLE_DIRECTION_API)

    payload = {'origin':start, 'destination':end}
    result = requests.get(DIRECTIONS_BASEURL, params=payload)
    result = result.json()
    responce = ''

    try:
        if result['status'] == "OK":
            for i in range (0, len (result['routes'][0]['legs'][0]['steps'])):
                j = result['routes'][0]['legs'][0]['steps'][i]['html_instructions']
                responce +=strip_tags(j)+'\n'

            return responce
        else:
            ''' Will be replaced with logging in future'''
            print(result['status'])
            print(result['error_message'])
            return ERROR_MSG
    except KeyError as e:
        ''' Need to be logged'''
        return ERROR_MSG 
开发者ID:Eulercoder,项目名称:fabulous,代码行数:26,代码来源:directions.py

示例14: cerca

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def cerca(cls, indirizzo):
        """
        Usa le API di Google (Geocode) per cercare l'indirizzo,
        ritorna una stringa (indirizzo formattato) per ogni risultato.

        :param indirizzo: Indirizzo da cercare
        :return: Lista di risultati.
        """
        try:
            gmaps = googlemaps.Client(key=GOOGLE_KEY)

        except ValueError:
            # API key not configured
            logger.warning("Chiave API Google non configurata. Le ricerche geografiche non ritorneranno "
                           "alcun risultato.")
            return []

        risultati = gmaps.geocode(indirizzo, region="it", language="it")
        return [
            (x['formatted_address'], cls.controlla_posizione(x['geometry']['location']),
             cls.scomponi_indirizzo(x))
            for x in risultati
        ] 
开发者ID:CroceRossaItaliana,项目名称:jorvik,代码行数:25,代码来源:geo.py

示例15: set_google_maps_fields

# 需要导入模块: import googlemaps [as 别名]
# 或者: from googlemaps import Client [as 别名]
def set_google_maps_fields(self, latlng=None):
        """
        Uses the Google Maps API to set:
          - geocoded latlng
          - nearest school name + distance
          - nearest train station name + distance
        """
        client = Client(key=settings.GOOGLE_MAPS_API_SERVER_KEY)
        if not latlng:
            data = client.geocode(self.address)
            if not data:
                raise Exception("Unable to resolve the address: '%s'" % address)
            latlng = data[0]["geometry"]["location"]
        self.point = GEOSGeometry("POINT(%(lng)s %(lat)s)" % latlng)

        error = ""
        for field in ("school", "train_station"):
            try:
                place = client.places_nearby(location=latlng, rank_by="distance", type=field)["results"][0]
            except IndexError:
                continue
            except Exception as e:
                error = e
                continue
            setattr(self, "nearest_%s" % field, place["name"])
            place_latlng = place["geometry"]["location"]
            d = distance((latlng["lat"], latlng["lng"]), (place_latlng["lat"], place_latlng["lng"])).km
            setattr(self, "nearest_%s_distance" % field, round(d, 2))
        if error:
            raise Exception(error) 
开发者ID:googlemaps,项目名称:property-finder,代码行数:32,代码来源:models.py


注:本文中的googlemaps.Client方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。