Python geopy.geocoders.Nominatim() Examples

The following are 16 code examples of geopy.geocoders.Nominatim(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module geopy.geocoders , or try the search function .
Example #1
Source File: gps.py    From X-tra-Telegram with Apache License 2.0 9 votes vote down vote up
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") 
Example #2
Source File: misc.py    From SkittBot with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: utils.py    From rosetta_recsys2019 with Apache License 2.0 6 votes vote down vote up
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 
Example #4
Source File: _import.py    From openmoves with MIT License 6 votes vote down vote up
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 
Example #5
Source File: weather.py    From quantified-self with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: loc.py    From hemppa with GNU General Public License v3.0 6 votes vote down vote up
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!") 
Example #7
Source File: mapsearch.py    From apex-sigma-core with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: mapper.py    From BackpackingMapper with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #9
Source File: where_have_you_been.py    From facebook-archive with MIT License 5 votes vote down vote up
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") 
Example #10
Source File: design_climate.py    From fluids with MIT License 5 votes vote down vote up
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 
Example #11
Source File: latlong.py    From SchoolIdolAPI with Apache License 2.0 5 votes vote down vote up
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() 
Example #12
Source File: cspm.py    From CSPM with MIT License 5 votes vote down vote up
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.') 
Example #13
Source File: analysis.py    From twitter-intelligence with MIT License 5 votes vote down vote up
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 
Example #14
Source File: community_events.py    From rasa-demo with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #15
Source File: tba.py    From Dozer with GNU General Public License v3.0 4 votes vote down vote up
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)"))) 
Example #16
Source File: KKTIX.py    From TGmeetup with MIT License 4 votes vote down vote up
def get_meetup_info(self, gfile, org_url):
        url_name = (str(org_url).split("/")[2].split(".")[0])
        get_event_url = "https://" + url_name + ".kktix.cc/events.json"
        result = requests.get(get_event_url)
        events_info = result.json()["entry"]
        events_list = []
        if len(events_info) == 0:
            return None
        else:
            for event in events_info:
                if event["published"].split("T")[0] > time.strftime(
                        "%Y-%m-%d", time.localtime()):
                    data = json.load(open(gfile))
                    geolocator = Nominatim(user_agent="TGmeetup")
                    try:
                        g = geolocator.geocode(data["city"])
                        while g.latitude is None:
                            g = geolocator.geocode(data["city"])
                    except BaseException:
                        g = geolocator.geocode(data["city"])
                        while g.latitude is None:
                            g = geolocator.geocode(data["city"])
                    events_list.append({
                        "name": event["title"],
                        "local_date": event["published"].split("T")[0],
                        "local_time": event["published"].split("T")[1].split(".")[0],
                        "location": event["content"].split(":".encode('utf-8').decode('utf-8'))[2],
                        "local_city": data["city"],
                        "geocodeFromGroup": "false",
                        "geocode": {
                            "lat": g.latitude,
                            "lng": g.longitude
                        },
                        "link": event["url"]})
                else:
                    break
            if len(events_list) == 0:
                return None
            else:
                if len(events_list) > 3:
                    sorted(events_list, key=lambda k: k['local_date'], reverse=True)
                return events_list