How to use the geopy.geocoders function in geopy

To help you get started, we’ve selected a few geopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nelsyeung / PoGoTools / pogotools.py View on Github external
# Read user config file
    with open('config.json', 'r') as f:
        config = json.load(f)['accounts'][args.account]

    # Check if location is latitude and longitude, or a name
    location = config['location'].split(',')
    try:
        latitude = float(location[0])
        longitude = float(location[1])
        logging.info('Location supplied is already in latitude and'
                     'longitude form')
    except ValueError:
        logging.info('Getting the longitude and latitude for %s',
                     config['location'])
        geolocator = geopy.geocoders.Nominatim()
        location = geolocator.geocode(config['location'])
        latitude = location.latitude
        longitude = location.longitude

    api = pgoapi.PGoApi()
    logging.info('Setting the position to %f, %f', latitude, longitude)
    api.set_position(latitude, longitude, 0.0)

    logging.info('Logging into %s', config['username'])
    if not api.login(config['auth_service'],
                     config['username'],
                     config['password']):
        logging.error('Login unsuccessful')
        logging.error('Perhaps Niantic server is down')
        sys.exit(1)
    logging.info('Logged into %s successfully', config['username'])
github GeoNode / geonode / geonode / contrib / worldmap / gazetteer / utils.py View on Github external
def getGoogleResults(place_name):
    if hasattr(settings, 'GOOGLE_SECRET_KEY'):
        g = geocoders.GoogleV3(
            client_id=settings.GOOGLE_API_KEY,
            secret_key=settings.GOOGLE_SECRET_KEY
        )
    else:
        g = geocoders.GoogleV3()
    try:
        results = g.geocode(place_name, exactly_one=False)
        formatted_results = []
        for result in results:
            formatted_results.append(formatExternalGeocode('Google', result))
        return formatted_results
    except Exception:
        return []
github alexhanna / hadoop / streaming / map / mentionMapper.py View on Github external
parser.add_argument('-g', '--geo', action = "store_true", help = "Add geolocation of source and target.")
    parser.add_argument('--dstk', help = """Name of the DataScienceToolKit server to use.
        You can use the www.datasciencetoolkit.org but it's probably more advisable to roll your own on Amazon S3.""")
    parser.add_argument('--printDate', action = "store_true")
    parser.add_argument('-r', '--rt', action = "store_true", help = "Only retweets.")
    parser.add_argument('-s', '--search', action = "store_true",
        help = "Structure of the tweet is slightly different in the search API.")

    args = parser.parse_args()

    if args.keywordFile:
        wordList = loadKeywords( args.keywordFile )

    ## set DSTK server
    if args.dstk:
        g = geocoders.GoogleV3(domain = args.dstk)

    for line in sys.stdin:
        line = line.strip()

        try:
            data = json.loads(line)
        except ValueError as detail:
            sys.stderr.write(detail.__str__() + "\n")
            continue

        if not (isinstance(data, dict)):
            ## not a dictionary, skip
            pass
        elif 'delete' in data:
            ## a delete element, skip for now.
            pass
github nrcharles / solpy / solpy / pv.py View on Github external
modules.Array(modules.Module(i["panel"]),\
                shape), (o["azimuth"], o["tilt"]))
                #i["series"],i["parallel"]))
        if "derate" in i:
            block.derate = i["derate"]
        json_shape += [block] * scale
    plant = System(json_shape)
    if 'station_class' in json_description:
        plant.set_zipcode(json_description["zipcode"], \
                json_description['station_class'])
    else:
        plant.set_zipcode(json_description["zipcode"])
    if "address" in json_description:
        plant.address = json_description["address"]
    try:
        geocoder = geocoders.GoogleV3()
        place, (lat, lng) = geocoder.geocode(plant.address)
        plant.place = lat, lng
    except:
        pass
        #print "%s, %s location from zipcode" % plant.place
    #print orientations
    #print set(["%s_%s" % (i['azimuth'],i['tilt']) for i in orientations])
    if len(set(["%s_%s" % (i['azimuth'], i['tilt']) for i in orientations])) \
            > 1:
        print "WARNING: multiple tilts not implimented"
        plant.tilt = o[0]["tilt"]
        plant.azimuth = o[0]["azimuth"]
    elif "tilt" in json_description and "azimuth" in json_description:
        plant.tilt = json_description["tilt"]
        plant.azimuth = json_description["azimuth"]
    else:
github dgraziotin / dycapo / server / models.py View on Github external
def address_to_point(self):
        """
        Given Geolocation information, it retrieves GeoRSS.
        the return value of geocoder.geocode is in the form
        (u'Street name, Street Number, Postcode City Province, Country', (latitude, longitude))
        """
        try:
            geocoder = geocoders.Google(GOOGLE_MAPS_API_KEY)
            address = self.street + ", " + str(self.postcode) + " " + self.town
            geo_info = geocoder.geocode(address)
            self.georss_point = str(geo_info[1][0]) + ' ' +str(geo_info[1][1])
            point = Point.from_string(self.georss_point)
            self.georss_point_latitude = point.latitude
            self.georss_point_longitude = point.longitude
        except:
            self.georss_point = "0 0"
            self.georss_point_latitude = 0
            self.georss_point_longitude = 0
            raise ValueError('Could not retrieve Address information with the given GeoRSS point')
        self.georss_point_latitude = point.latitude
        self.georss_point_longitude = point.longitude
github Code4HR / hrt-bus-api / web / app.py View on Github external
def getStopsNearIntersection(city, intersection):
    place, (lat, lng) = geocoders.googlev3.GoogleV3().geocode(
        "{0}, {1}, VA".format(intersection, city), exactly_one=False)[0]
    return getStopsNear(lat, lng)
github staterepme / State-Gov-Tracker / state_gov_tracker_app / cicero_search.py View on Github external
def geocode_address(self, origin_address):
        """Geocodes an address string
        Filters results by settings.STATE
        Sets self.lat/lng to result
        Throws exceptions if the number of results isn't exactly 1
        """
        self.places = []
        b = geocoders.Bing(settings.BING_KEY)
        try:
            place, (lat, lng) = b.geocode(origin_address)
            self.places.append((place, lat, lng))
        except ValueError:
            for result in b.geocode(origin_address, exactly_one=False):
                place, (lat, lng) = result
                self.places.append((place, lat, lng))
        except:
            self.places.append(None)

        self.places = _filter_addresses(self.places)
        if len(self.places) > 1:
            raise ValueError("More than one location found")
        if len(self.places) == 0:
            raise LookupError("No Locations in PA found")
        else:
github adam-p / danforth-east / helpers.py View on Github external
address_components = [
        record_dict.get(fields.street_num.name),
        record_dict.get(fields.street_name.name),
        record_dict.get(fields.city.name) or 'Toronto',
        'Ontario',
        record_dict.get(fields.postal_code.name),
        'Canada',
    ]

    # Get rid of the empty components
    address_components = [component for component in address_components if component]

    address_string = ', '.join(address_components)

    geocoder = geopy.geocoders.GoogleV3(config.GOOGLE_SERVER_API_KEY)

    try:
        location = geocoder.geocode(address_string, region='CA')
    except Exception as e:
        logging.error('geocode failed: %s', exc_info=e)
        return ''

    if not location:
        return ''

    return '%s, %s' % (location.latitude, location.longitude)
github goldsmith / ruby-projects / Numbers / distance.py View on Github external
geopy
    pip install geopy
"""

from geopy import geocoders # to find lat/lon for the city
import math

R = 6373 # km

city1 = raw_input('Enter city 1: ')
city2 = raw_input('Enter city 2: ')
unit = raw_input('Enter unit of distance (Enter "K" for KM or "M" for MI): ').lower()

if unit in 'km':

    g = geocoders.GoogleV3()
    
    try:
        city1, (lat1, lon1) = g.geocode(city1)
        city2, (lat2, lon2) = g.geocode(city2)
    except:
        raise Exception('Unable to locate the citites. Check the city names.')
    
    # convert decimal locations to radians
    lat1 = math.radians(lat1)
    lon1 = math.radians(lon1)
    lat2 = math.radians(lat2)
    lon2 = math.radians(lon2)
    
    # start haversne formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
github M4rtinK / modrana / modules / mod_onlineServices / geocoding.py View on Github external
def geocode(address):
    from geopy import geocoders

    g = geocoders.Google()
    try:
        places = list(g.geocode(address, exactly_one=False))
        return _places2points(places)
    except Exception:
        log.exception("geocoding exception")
        return []