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


Python geocoders.Nominatim方法代码示例

本文整理汇总了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 
开发者ID:skittles9823,项目名称:SkittBot,代码行数:20,代码来源:misc.py

示例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 
开发者ID:rosetta-ai,项目名称:rosetta_recsys2019,代码行数:19,代码来源:utils.py

示例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 
开发者ID:bwaldvogel,项目名称:openmoves,代码行数:19,代码来源:_import.py

示例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) 
开发者ID:DongjunLee,项目名称:quantified-self,代码行数:36,代码来源:weather.py

示例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!") 
开发者ID:vranki,项目名称:hemppa,代码行数:22,代码来源:loc.py

示例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) 
开发者ID:lu-ci,项目名称:apex-sigma-core,代码行数:27,代码来源:mapsearch.py

示例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") 
开发者ID:Dark-Princ3,项目名称:X-tra-Telegram,代码行数:32,代码来源:gps.py

示例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") 
开发者ID:kaustubhhiware,项目名称:facebook-archive,代码行数:12,代码来源:where_have_you_been.py

示例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 
开发者ID:CalebBell,项目名称:fluids,代码行数:15,代码来源:design_climate.py

示例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() 
开发者ID:MagiCircles,项目名称:SchoolIdolAPI,代码行数:29,代码来源:latlong.py

示例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.') 
开发者ID:rkhous,项目名称:CSPM,代码行数:12,代码来源:cspm.py

示例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 
开发者ID:batuhaniskr,项目名称:twitter-intelligence,代码行数:35,代码来源:analysis.py

示例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 
开发者ID:RasaHQ,项目名称:rasa-demo,代码行数:16,代码来源:community_events.py

示例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) 
开发者ID:JKesslerPhD,项目名称:BackpackingMapper,代码行数:9,代码来源:mapper.py

示例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)"))) 
开发者ID:FRCDiscord,项目名称:Dozer,代码行数:50,代码来源:tba.py


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