Python geopy.geocoders.GoogleV3() Examples

The following are 13 code examples of geopy.geocoders.GoogleV3(). 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: __init__.py    From PokemonGo-Bot with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: example.py    From PokemonGo-SlackBot with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: pokehomey.py    From PokemonGo-SlackBot with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: pokeslack.py    From PokemonGo-SlackBot with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: __init__.py    From PokemonGo-Bot-Backup with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: geoip.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def query_google(latitude, longitude):
        coordinates = "%s, %s" % (latitude, longitude)
        Logger.log_more_verbose(
            "Querying Google Geocoder for: %s" % coordinates)
        try:
            g = geocoders.GoogleV3()
            r = g.reverse(coordinates)
            if r:
                return r[0][0].encode("UTF-8")
        except Exception, e:
            fmt = traceback.format_exc()
            Logger.log_error_verbose("Error: %s" % str(e))
            Logger.log_error_more_verbose(fmt)


    #-------------------------------------------------------------------------- 
Example #7
Source File: geocoding.py    From twitter with MIT License 5 votes vote down vote up
def __init__(self):
        self.geocoder = GoogleV3()
        self.updated_tweets = [] 
Example #8
Source File: location.py    From connect with MIT License 5 votes vote down vote up
def geocode_location(location):
    """Geocode a location string using Google geocoder."""
    geocoder = geocoders.GoogleV3()
    try:
        result = geocoder.geocode(location, exactly_one=False)
    except Exception:
        return None, None
    try:
        ctr_lat, ctr_lng = result[0][1]
    except IndexError:
        return None, None

    return clean_coords(coords=(ctr_lat, ctr_lng)) 
Example #9
Source File: utilities.py    From pogom with MIT License 5 votes vote down vote up
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) 
Example #10
Source File: utilities.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
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) 
Example #11
Source File: pokeutil.py    From pokeslack with MIT License 5 votes vote down vote up
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') 
Example #12
Source File: api_wrapper.py    From PokemonGo-Bot with MIT License 4 votes vote down vote up
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 
Example #13
Source File: geocoder.py    From radremedy with Mozilla Public License 2.0 4 votes vote down vote up
def geocode(self, resource):
        """
        Performs geocoding on the provided resource and updates its formatted
        address, latitude, and longitude.

        Args:
            resource: A resource from which the address components will be
                retrieved and used to update its formatted address,
                latitude, and longitude.

        Raises:
            geopy.exc.GeopyError: An error occurred attempting to access the
                geocoder.
        """

        # Make sure we generated something meaningful
        if resource.address is not None and not resource.address.isspace():
            # Now query the geocoder with this formatted string
            geolocator = GoogleV3(api_key=self.api_key)

            new_location = geolocator.geocode(
                resource.address,
                exactly_one=True)

            if new_location is not None:
                new_res_location = ''

                if new_location.address and \
                        not new_location.address.isspace():
                    resource.address = new_location.address

                if new_location.latitude is not None and \
                        new_location.longitude is not None:
                    resource.latitude = new_location.latitude
                    resource.longitude = new_location.longitude

                # Look at the raw response for address components
                if new_location.raw:
                    address_components = new_location.raw.get(
                        'address_components')

                    if address_components:
                        # Get the city/county/state strings
                        city_str, county_str, state_str = \
                            self.get_locality_strings(address_components)

                        # Now build the location based on those strings,
                        # preferring city to county
                        new_res_location = city_str or county_str or ''

                        if state_str:
                            # Add a comma and space between the city/county
                            # and state
                            if new_res_location:
                                new_res_location = new_res_location + ', '

                            new_res_location = new_res_location + state_str

                # After all of that, update the location
                resource.location = new_res_location
        pass