我们从Python开源项目中,提取了以下35个代码示例,用于说明如何使用geopy.geocoders.GoogleV3()。
def get_pos_by_name(self, location_name): # Check if given location name, belongs to favorite_locations favorite_location_coords = self._get_pos_by_fav_location(location_name) if favorite_location_coords is not None: return favorite_location_coords # Check if the given location is already a coordinate. if ',' in location_name: possible_coordinates = re.findall( "[-]?\d{1,3}(?:[.]\d+)?", location_name ) if len(possible_coordinates) >= 2: # 2 matches, this must be a coordinate. We'll bypass the Google # geocode so we keep the exact location. self.logger.info( '[x] Coordinates found in passed in location, ' 'not geocoding.' ) return float(possible_coordinates[0]), float(possible_coordinates[1]), (float(possible_coordinates[2]) if len(possible_coordinates) == 3 else self.alt) geolocator = GoogleV3(api_key=self.config.gmapkey) loc = geolocator.geocode(location_name, timeout=10) return float(loc.latitude), float(loc.longitude), float(loc.altitude)
def set_location(location_name): geolocator = GoogleV3() prog = re.compile('^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$') global origin_lat global origin_lon if prog.match(location_name): local_lat, local_lng = [float(x) for x in location_name.split(",")] alt = 0 origin_lat, origin_lon = local_lat, local_lng else: loc = geolocator.geocode(location_name) origin_lat, origin_lon = local_lat, local_lng = loc.latitude, loc.longitude alt = loc.altitude print '[!] Your given location: {}'.format(loc.address.encode('utf-8')) print('[!] lat/long/alt: {} {} {}'.format(local_lat, local_lng, alt)) set_location_coords(local_lat, local_lng, alt)
def _geolocate_google(self, string): g = GoogleV3() try: results = g.geocode(string, region='za') # Has it actually managed to find coords beyond province level? and are we in the right country? country = '' for address_component in results.raw['address_components']: if address_component['types'] == ['country', 'political']: country = address_component['short_name'] if country == 'ZA': # Get geographical position coords = results.raw['geometry']['location'] ac = results.raw['address_components'][0] self.add_potential_georeference(long=coords['lng'], lat=coords['lat'], profile_name='Google', locality_name=ac['short_name']) except AttributeError as e: print("Google - not found: " + string + ' gives error : ' + str(sys.exc_info())) return False
def get_pos_by_name(location_name): prog = re.compile("^(\-?\d+\.\d+)?,\s*(\-?\d+\.\d+?)$") res = prog.match(location_name) latitude, longitude, altitude = None, None, None if res: latitude, longitude, altitude = float(res.group(1)), float(res.group(2)), 0 else: geolocator = GoogleV3() loc = geolocator.geocode(location_name, timeout=10) if loc: log.info("Location for '%s' found: %s", location_name, loc.address) log.info('Coordinates (lat/long/alt) for location: %s %s %s', loc.latitude, loc.longitude, loc.altitude) latitude, longitude, altitude = loc.latitude, loc.longitude, loc.altitude else: return None return (latitude, longitude, altitude)
def get_pos_by_name(self, location_name): # Check if given location name, belongs to favorite_locations favorite_location_coords = self._get_pos_by_fav_location(location_name) if favorite_location_coords is not None: return favorite_location_coords # Check if the given location is already a coordinate. if ',' in location_name: possible_coordinates = re.findall( "[-]?\d{1,3}[.]\d{3,7}", location_name ) if len(possible_coordinates) >= 2: # 2 matches, this must be a coordinate. We'll bypass the Google # geocode so we keep the exact location. self.logger.info( '[x] Coordinates found in passed in location, ' 'not geocoding.' ) return float(possible_coordinates[0]), float(possible_coordinates[1]), (float(possible_coordinates[2]) if len(possible_coordinates) == 3 else self.alt) geolocator = GoogleV3(api_key=self.config.gmapkey) loc = geolocator.geocode(location_name, timeout=10) return float(loc.latitude), float(loc.longitude), float(loc.altitude)
def address_from_row(row): geocoder = GoogleV3(settings.GOOGLE_MAPS_API_KEY) addr_to_geocode = "" if 'full_address' in row and len(row['full_address']) > 0: addr_to_geocode = row['address'] elif 'zipcode' in row and len(row['zipcode']) > 0: addr_to_geocode = row['zipcode'] elif 'city' in row and len(row['city']) > 0: addr_to_geocode = row['city'] if addr_to_geocode is None: logging.debug("Could not find suitable geocode field") return None if addr_to_geocode not in __addr_cache: geocoded = None try: geocoded = geocoder.geocode(addr_to_geocode) except: pass if geocoded: ret = translate_google_result(geocoded.raw) __addr_cache[addr_to_geocode] = ret else: __addr_cache[addr_to_geocode] = addr_to_geocode logging.debug("%s -> %r", addr_to_geocode, __addr_cache[addr_to_geocode]) return __addr_cache[addr_to_geocode]
def gAPI(locat,hwy, city, link, f): #Location is discription ,city, link is to URL, f is file time.sleep(0.2); geolocator = GoogleV3() try: searchTerm = str(locat + ',' + city + ', WI, US') #Search for location and city location = geolocator.geocode(searchTerm) except: try: searchTerm = str(hwy + ',' + city + ', WI, US') #Search for hwy and city location = geolocator.geocode(searchTerm) except: searchTerm = str(city + ', WI, US') #Search for only city location = geolocator.geocode(searchTerm) extractCity = location.raw['address_components'] #Get the raw JSON information so that the city name can be extracted for item in extractCity: types = item['types'] if types[0] == "locality": city = item['long_name'] # print locat, hwy, city # print location.latitude, location.longitude locat = 'USA'+'#'+'WI'+'#'+str(city)+'#'+link+'#'+str(location.latitude)+'#'+str(location.longitude) f.write(locat.encode('utf-8').replace(" ","").replace("\n",'')+'\n') return;
def __init__(self, locationLookup, geo_key, noop=False): # Blank location if noop: self.noop = True self.geo_key = None self.locator = None self.latitude = None self.longitude = None self.altitude = None return self.noop = False self.geo_key = geo_key self.locator = GoogleV3() if geo_key: self.locator = GoogleV3(api_key=geo_key) self.latitude, self.longitude, self.altitude = self.setLocation(locationLookup)
def get_pos_by_name(location_name): prog = re.compile("^(\-?\d+\.\d+)?,\s*(\-?\d+\.\d+?)$") res = prog.match(location_name) if res: latitude, longitude, altitude = float(res.group(1)), float(res.group(2)), 0 else: geolocator = GoogleV3() loc = geolocator.geocode(location_name, timeout=10) if loc: log.info("Location for '%s' found: %s", location_name, loc.address) log.info('Coordinates (lat/long/alt) for location: %s %s %s', loc.latitude, loc.longitude, loc.altitude) latitude, longitude, altitude = loc.latitude, loc.longitude, loc.altitude else: return None return (latitude, longitude, altitude)
def forecast(self, timely='current'): geolocator = GoogleV3() location = geolocator.geocode(self.profile.get_location()) api_key = Config.open_api.dark_sky.TOKEN lat = location.latitude lon = location.longitude dark_sky = forecastio.load_forecast(api_key, lat, lon) if timely == 'current': currently = dark_sky.currently() self.__forecast(currently, timely, location.address) elif timely == 'daily': hourly = dark_sky.hourly() self.__forecast(hourly, timely, location.address) elif timely == 'weekly': daily = dark_sky.daily() self.__forecast(daily, timely, location.address)
def get_pos_by_name(location_name): geolocator = GoogleV3() loc = geolocator.geocode(location_name, timeout=10) if not loc: return None log.info("Location for '%s' found: %s", location_name, loc.address) log.info('Coordinates (lat/long/alt) for location: %s %s %s', loc.latitude, loc.longitude, loc.altitude) return (loc.latitude, loc.longitude, loc.altitude)
def get_coordinates(location): geolocator = GoogleV3() target = geolocator.geocode(location) return {'lat': str(target.latitude), 'long': str(target.longitude)}
def ex(dclient, channel, mention, a, cmd_char): if len(a) > 0: g = geocoders.GoogleV3() try: place, (lat, lng) = g.geocode(a) timezone = g.timezone((lat, lng)) time_now = datetime.now(timezone) await dclient.send_message(channel, 'It is `{:%H:%M:%S}` or `{:%I:%M:%S %p}` in `{}` right now.' .format(time_now, time_now, a)) except Exception: await dclient.send_message(channel, 'Location `{}` unknown! Please try to be more specific! I rely on ' 'Google maps to get the coordinates for the timezone, {}!' .format(a, mention)) else: await dclient.send_message(channel, '{}, **USAGE:** {}time <location>'.format(mention, cmd_char))
def _get_default_pool_members(): from geopy.geocoders import Nominatim, GoogleV3 return (Nominatim(), GoogleV3())
def get_pos_by_name(location_name): geolocator = GoogleV3() loc = geolocator.geocode(location_name, timeout=10) logger.debug('location: %s', loc.address.encode('utf-8')) logger.debug('lat, long, alt: %s, %s, %s', loc.latitude, loc.longitude, loc.altitude) return (loc.latitude, loc.longitude, loc.altitude), loc.address.encode('utf-8')
def get_pos_by_name(location_name): prog = re.compile("^(\-?\d+\.\d+)?,\s*(\-?\d+\.\d+?)$") res = prog.match(location_name) latitude, longitude, altitude = None, None, None if res: latitude, longitude, altitude = float(res.group(1)), float(res.group(2)), 0 elif location_name: geolocator = GoogleV3() loc = geolocator.geocode(location_name) if loc: latitude, longitude, altitude = loc.latitude, loc.longitude, loc.altitude return (latitude, longitude, altitude)
def on_enter_receive_user_address(self, event): coder = GoogleV3() address = event.message.text geocode = coder.geocode(address) if geocode: hospital_list = hospital.utils.get_nearby_hospital(geocode.longitude, geocode.latitude) self._send_hospital_msgs(hospital_list, event) self.finish_ans() else: # Invalid address self._send_text_in_rule(event, 'invalid_address') self.finish_ans()
def set_location(location_name): geolocator = GoogleV3() loc = geolocator.geocode(location_name) print('[!] Your given location: {}'.format(loc.address.encode('utf-8'))) print('[!] lat/long/alt: {} {} {}'.format(loc.latitude, loc.longitude, loc.altitude)) set_location_coords(loc.latitude, loc.longitude, loc.altitude)
def get_location(latitude, longitude): geolocator = GoogleV3(api_key=os.environ.get("GOOGLE_API_KEY")) location = geolocator.reverse("{latitude}, {longitude}".format( latitude=latitude, longitude=longitude, )) if not location: result = { "country": None, "city": None, } return result elements = location[0].raw.get("address_components") address_components = [ { element.get("types")[0]: element.get("long_name"), } for element in elements ] address_dict = {} for address_component in address_components: for key, value in address_component.items(): address_dict[key] = value if address_dict.get("locality"): city = address_dict.get("locality") city = address_dict.get("administrative_area_level_1") country = address_dict.get("country") result = { "country": country, "city": city, } return result
def gAPI(self, locat, region, main_location, country, link, f, g): time.sleep(0.2); geolocator = GoogleV3(api_key = 'AIzaSyDRb6HaVtHDbpHkJq8a3MEODFZlmkBt7f4') if country != 'USA': try: searchTerm = str(locat + region + ',' + country) location = geolocator.geocode(searchTerm) except: searchTerm = str(main_location + ',' + country) location = geolocator.geocode(searchTerm) extractCity = location.raw['address_components'] #Get the raw JSON information so that the city name can be extracted city = locat for item in extractCity: types = item['types'] if types[0] == "locality": city = item['long_name'] locat = country+'#'+str(city).decode("utf-8")+'#'+link+'#'+str(location.latitude)+'#'+str(location.longitude) f.write(locat.encode('utf-8').replace(" ","").replace("\n",'')+'\n') else: try: searchTerm = str(locat + region + ',' + main_location) location = geolocator.geocode(searchTerm) except: raise Exception extractCityState = location.raw['address_components'] #Get the raw JSON information so that the city name can be extracted city = locat state = "" for item in extractCityState: types = item['types'] if types[0] == "locality": city = item['long_name'] elif types[0] == "administrative_area_level_1": state = item['short_name'] if state == "": raise Exception('No State!') locat = 'USA#'+str(state)+'#'+str(city).decode("utf-8")+'#'+link+'#'+str(location.latitude)+'#'+str(location.longitude) g.write(locat.encode('utf-8').replace(" ","").replace("\n",'')+'\n')
def __init__(self, source, key): if source == 'Google': self.geolocator = GoogleV3(api_key = key) if source == 'Nominatim': self.geolocator = Nominatim() self.latitude = "" self.longitude = "" self.city = "" self.state = "" self.country = "" reload(sys) sys.setdefaultencoding('utf8')
def get_pos_by_name(location_name): geolocator = GoogleV3() loc = geolocator.geocode(location_name, timeout=10) return (loc.latitude, loc.longitude, loc.altitude)
def get_pos_by_name(location_name): geolocator = GoogleV3() loc = geolocator.geocode(location_name) if not loc: return None log.info('Your given location: %s', loc.address.encode('utf-8')) log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude) return (loc.latitude, loc.longitude, loc.altitude)
def set_location(location_name): geolocator = GoogleV3() prog = re.compile('^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$') global origin_lat global origin_lon global coords global args updateLocation() location_name = '' print '--------------------------------' if str(args.port) in coords: if coords[str(args.port)] == "": location_name = 'Durango, Dgo.' else: location_name = coords[str(args.port)] else: location_name = 'Durango, Dgo.' print location_name print '--------------------------------' if prog.match(location_name): local_lat, local_lng = [float(x) for x in location_name.split(",")] alt = 0 origin_lat, origin_lon = local_lat, local_lng else: loc = geolocator.geocode(location_name) origin_lat, origin_lon = local_lat, local_lng = loc.latitude, loc.longitude alt = loc.altitude print '[!] Your given location: {}'.format(loc.address.encode('utf-8')) print('[!] lat/long/alt: {} {} {}'.format(local_lat, local_lng, alt)) set_location_coords(local_lat, local_lng, alt)
def cli(ctx, position): config = ctx.obj.get('config') # TODO: include google api key here geocoder = GoogleV3() try: loc = geocoder.geocode(position) if not loc: click.secho( 'Could not geocode the specified location, aborting…', fg='red' ) return False click.secho( 'Found position: {}'.format(loc.address.encode('utf8')), fg='cyan' ) config.position = dict( text=loc.address, latitude=loc.latitude, longitude=loc.longitude, altitude=loc.altitude ) config.save() except GeocoderQueryError: click.secho( 'Could not geocode the specified location, aborting…', fg='red' ) return False
def login(self, provider, username, password): # login needs base class "create_request" self.useVanillaRequest = True # Get Timecode and Country Code country_code = "US" timezone = "America/Chicago" geolocator = GoogleV3(api_key=self.config.gmapkey) if self.config.locale_by_location: try: location = geolocator.reverse((self.actual_lat, self.actual_lng), timeout = 10, exactly_one=True) country_code = self.get_component(location,'country') except: self.logger.warning("Please make sure you have google api key and enable Google Maps Geocoding API at console.developers.google.com") try: timezone = geolocator.timezone([self.actual_lat, self.actual_lng], timeout=10) except: self.logger.warning("Please make sure you have google api key and enable Google Maps Time Zone API at console.developers.google.com") # Start login process try: if self.config.proxy: PGoApi.set_authentication( self, provider, username=username, password=password, proxy_config={'http': self.config.proxy, 'https': self.config.proxy} ) else: PGoApi.set_authentication( self, provider, username=username, password=password ) except: raise try: if self.config.locale_by_location: response = PGoApi.app_simulation_login(self,country_code,timezone.zone) else: response = PGoApi.app_simulation_login(self) # To prevent user who have not update the api being caught off guard by errors except BadHashRequestException: self.logger.warning("Your hashkey seems to have expired or is not accepted!") self.logger.warning("Please set a valid hash key in your auth JSON file!") exit(-3) raise except BannedAccountException: self.logger.warning("This account is banned!") exit(-3) raise except: raise # cleanup code self.useVanillaRequest = False return response