本文整理匯總了Python中geopy.geocoders.Nominatim方法的典型用法代碼示例。如果您正苦於以下問題:Python geocoders.Nominatim方法的具體用法?Python geocoders.Nominatim怎麽用?Python geocoders.Nominatim使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類geopy.geocoders
的用法示例。
在下文中一共展示了geocoders.Nominatim方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: gps
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def gps(bot: Bot, update: Update, args: List[str]):
message = update.effective_message
try:
geolocator = Nominatim(user_agent="SkittBot")
location = " ".join(args)
geoloc = geolocator.geocode(location)
chat_id = update.effective_chat.id
lon = geoloc.longitude
lat = geoloc.latitude
the_loc = Location(lon, lat)
gm = "https://www.google.com/maps/search/{},{}".format(lat,lon)
bot.send_location(chat_id, location=the_loc)
message.reply_text("Open with: [Google Maps]({})".format(gm), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
except AttributeError:
message.reply_text("I can't find that")
# /ip is for private use
示例2: location2utc_offset
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def location2utc_offset(location):
'''
return the utc offset given the location
'''
geolocator = Nominatim(user_agent=str(location))
# print(location)
location = geolocator.geocode(location)
if location == None:
return np.nan
try:
lat = location.latitude
lon = location.longitude
offset_sec = datetime.datetime.now(pytz.timezone(tzf.timezone_at(lng=lon, lat=lat)))
return offset_sec.utcoffset().total_seconds()/60/60
except:
return np.nan
示例3: postprocess_move
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def postprocess_move(move):
if move.public is None:
move.public = False
gps_samples = [sample for sample in move.samples if sample.sample_type and sample.sample_type.startswith('gps-')]
if gps_samples:
first_sample = gps_samples[0]
latitude = first_sample.latitude
longitude = first_sample.longitude
if latitude and longitude:
geo_locator = Nominatim(user_agent='openmoves.net')
location = geo_locator.reverse("%f, %f" % (radian_to_degree(latitude), radian_to_degree(longitude)), timeout=60)
move.location_address = location.address
move.location_raw = location.raw
示例4: forecast
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def forecast(self, timely="current"):
cache_data = self.data_handler.read_cache()
user_location = self.profile.get_location()
parsed_user_location = parse.quote(user_location) # user_location is Korean
if parsed_user_location in cache_data:
address = cache_data[parsed_user_location]["address"]
lat = cache_data[parsed_user_location]["lat"]
lon = cache_data[parsed_user_location]["lon"]
else:
geolocator = Nominatim(user_agent="kino-bot")
location = geolocator.geocode(user_location)
address = location.address
lat = location.latitude
lon = location.longitude
self.data_handler.edit_cache(
(parsed_user_location, {"address": address, "lat": lat, "lon": lon})
)
api_key = Config.open_api.dark_sky.TOKEN
dark_sky = forecastio.load_forecast(api_key, lat, lon)
if timely == "current":
currently = dark_sky.currently()
self.__forecast(currently, timely, address)
elif timely == "daily":
hourly = dark_sky.hourly()
self.__forecast(hourly, timely, address)
elif timely == "weekly":
daily = dark_sky.daily()
self.__forecast(daily, timely, address)
示例5: matrix_message
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def matrix_message(self, bot, room, event):
args = event.body.split()
args.pop(0)
if len(args) == 0:
await bot.send_text(room, 'Usage: !loc <location name>')
else:
query = event.body[4:]
geolocator = Nominatim(user_agent=bot.appid)
self.logger.info('loc: looking up %s ..', query)
location = geolocator.geocode(query)
self.logger.info('loc rx %s', location)
if location:
locationmsg = {
"body": str(location.address),
"geo_uri": 'geo:' + str(location.latitude) + ',' + str(location.longitude),
"msgtype": "m.location",
}
await bot.client.room_send(room.room_id, 'm.room.message', locationmsg)
else:
await bot.send_text(room, "Can't find " + query + " on map!")
示例6: mapsearch
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def mapsearch(_cmd, pld):
"""
:param _cmd: The command object referenced in the command.
:type _cmd: sigma.core.mechanics.command.SigmaCommand
:param pld: The payload with execution data and details.
:type pld: sigma.core.mechanics.payload.CommandPayload
"""
if pld.args:
search = ' '.join(pld.args)
search_url = '+'.join(pld.args)
geo_parser = Nominatim()
location = geo_parser.geocode(search)
if location:
lat = location.latitude
lon = location.longitude
maps_url = f'https://www.google.rs/maps/search/{search_url}/@{lat},{lon},11z?hl=en'
response = discord.Embed(color=0xdd4e40)
response.set_author(name=f'{location}', icon_url=map_icon, url=maps_url)
else:
maps_url = f'https://www.google.rs/maps/search/{search_url}'
response = discord.Embed(color=0xdd4e40)
response.set_author(name=f'Broad Search: {search.title()}', icon_url=map_icon, url=maps_url)
else:
response = error('Nothing inputted.')
await pld.msg.channel.send(embed=response)
示例7: gps
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def gps(event):
if event.fwd_from:
return
reply_to_id = event.message
if event.reply_to_msg_id:
reply_to_id = await event.get_reply_message()
input_str = event.pattern_match.group(1)
if not input_str:
return await event.edit("what should i find give me location.")
await event.edit("finding")
geolocator = Nominatim(user_agent="catuserbot")
geoloc = geolocator.geocode(input_str)
if geoloc:
lon = geoloc.longitude
lat = geoloc.latitude
await reply_to_id.reply(
input_str,
file=types.InputMediaGeoPoint(
types.InputGeoPoint(
lat, lon
)
)
)
await event.delete()
else:
await event.edit("i coudn't find it")
示例8: coord2address
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def coord2address(locations):
"""
:params locations: The locations whose address is to be found
Prints the address corresponding to the coordinates passed.
"""
geolocator = Nominatim(user_agent="location-finder" )
for i in locations:
coordinate = "{0}, {1}".format(i[0], i[1])
location = geolocator.reverse(coordinate)
print(location.address, "\n")
示例9: geopy_geolocator
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def geopy_geolocator():
'''Lazy loader for geocoder from geopy. This currently loads the
`Nominatim` geocode and returns an instance of it, taking ~2 us.
'''
global geolocator
if geolocator is None:
try:
from geopy.geocoders import Nominatim
except ImportError:
return None
geolocator = Nominatim(user_agent=geolocator_user_agent)
return geolocator
return geolocator
示例10: latlong
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def latlong(opt):
reload, retry = opt['reload'], opt['retry']
map = models.UserPreferences.objects.filter(location__isnull=False).exclude(location__exact='')
if not reload:
map = map.filter(location_changed__exact=True)
geolocator = Nominatim()
for user in map:
getLatLong(geolocator, user, retry)
map = models.UserPreferences.objects.filter(latitude__isnull=False).select_related('user')
mapcount = map.count()
f = open('mapcount.json', 'w')
print >> f, mapcount
f.close()
mapcache = ""
for u in map:
mapcache += " {'username': '%s',\
'avatar': '%s',\
'location': '%s',\
'icon': '%s',\
'latlong': new google.maps.LatLng(%f, %f) },\
" % (escape(u.user.username), escape(getUserAvatar(u.user, 200)), escape(u.location), escape(chibiimage(u.best_girl if u.best_girl else 'Alpaca', small=True, force_first=True)), u.latitude, u.longitude)
with open('map.json', 'w') as f:
f.write(mapcache.encode('UTF-8'))
f.close()
示例11: coords
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def coords(*, message:str):
geo = Nominatim()
coord = geo.geocode(str(message))
try:
await bot.say('The coordinates you requested for the address are shown below, you can now copy and paste it for the spawn command.')
await bot.say(str(coord.latitude) + ' ' + str(coord.longitude))
except:
tb = traceback.print_exc(file=sys.stdout)
print(tb)
await bot.say('An error has occurred processing your request.')
示例12: location_analysis
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def location_analysis():
with sqlite3.connect(db_path) as db:
conn = db
c = conn.cursor()
locxy = []
c.execute("Select place from location")
loc_array = c.fetchall()
# mapping
geo_data = {
"features": []
}
for x in range(len(loc_array)):
if (loc_array[x] != ''):
geolocator = Nominatim()
location = geolocator.geocode(loc_array[x])
locxy.append(location.latitude)
locxy.append(location.longitude)
geo_json_feature = {
"lat": location.latitude,
"lng": location.longitude
}
geo_data['features'].append(geo_json_feature)
locxy.clear()
json_location = json.dumps(geo_data)
print(colored("[INFO] Showing graph of location analysis", "green"))
return json_location
示例13: get_country_for
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def get_country_for(city: Text) -> Optional[Text]:
from geopy.geocoders import Nominatim
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
geo_locator = Nominatim(ssl_context=ssl_context)
location = geo_locator.geocode(city, language="en", addressdetails=True)
if location:
return location.raw["address"].get("country")
return None
示例14: LocationName
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def LocationName(location):
geolocator = Nominatim(user_agent="testing app")
try:
location = geolocator.geocode(location)
except:
raise Exception("There was a problem with the geolocator function")
return (location.latitude, location.longitude)
示例15: timezone
# 需要導入模塊: from geopy import geocoders [as 別名]
# 或者: from geopy.geocoders import Nominatim [as 別名]
def timezone(self, ctx, team_num: int, team_program="frc"):
"""
Get the timezone of a team based on the team number.
"""
if team_program.lower() == "frc":
try:
team_data = await self.session.team(team_num)
except aiotba.http.AioTBAError:
raise BadArgument('Team {} does not exist.'.format(team_num))
if team_data.city is None:
raise BadArgument("team {} exists, but does not have sufficient information!".format(team_num))
elif team_program.lower() == "ftc":
res = json.loads(await self.bot.cogs['TOA'].parser.req("team/{}".format(str(team_num))))
if not res:
raise BadArgument('Team {} does not exist.'.format(team_num))
team_data_dict = res[0]
team_data = self.TeamData()
team_data.__dict__.update(team_data_dict)
else:
raise BadArgument('`team_program` should be one of [`frc`, `ftc`]')
location = '{0.city}, {0.state_prov} {0.country}'.format(team_data)
gmaps = googlemaps.Client(key=self.gmaps_key)
geolocator = Nominatim(user_agent="Dozer Discord Bot")
geolocation = geolocator.geocode(location)
if self.gmaps_key and not self.bot.config['tz_url']:
timezone = gmaps.timezone(location="{}, {}".format(geolocation.latitude, geolocation.longitude),
language="json")
utc_offset = float(timezone["rawOffset"]) / 3600
if timezone["dstOffset"] == 3600:
utc_offset += 1
tzname = timezone["timeZoneName"]
else:
async with async_timeout.timeout(5), self.bot.http_session.get(urljoin(base=self.bot.config['tz_url'],
url="{}/{}".format(
geolocation.latitude,
geolocation.longitude))) as r:
r.raise_for_status()
data = await r.json()
utc_offset = data["utc_offset"]
tzname = '`{}`'.format(data["tz"])
current_time = datetime.datetime.utcnow() + datetime.timedelta(hours=utc_offset)
await ctx.send("Timezone: {} UTC{}\n{}".format(tzname, utc_offset, current_time.strftime("Current Time: %I:%M:%S %p (%H:%M:%S)")))