def test_geocode(self):
     addr = u'1600 amphithéatre mountain view ca'
     gmaps = GoogleMaps(GMAPS_API_KEY)
     results = gmaps.geocode(addr)
     first = results[0]
     for info in ({'long_name': '1600',
                   'short_name': '1600',
                   'types': ['street_number']},
                  {'long_name': 'Amphitheatre Parkway',
                   'short_name': 'Amphitheatre Pkwy',
                   'types': ['route']},
                  {'long_name': 'Mountain View',
                   'short_name': 'Mountain View',
                   'types': ['locality', 'political']},
                  {'long_name': '94043',
                   'short_name': '94043',
                   'types': ['postal_code']},
                  {'long_name': 'Santa Clara County',
                   'short_name': 'Santa Clara County',
                   'types': ['administrative_area_level_2', 'political']},
                  {'long_name': 'California',
                   'short_name': 'CA',
                   'types': ['administrative_area_level_1', 'political']},
                  {'long_name': 'United States',
                   'short_name': 'US',
                   'types': ['country', 'political']}):
         self.assertIn(info, first['address_components'])
     self.assertEqual(first['formatted_address'],
                      '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA')
     location = first['geometry']['location']
     self.assertAlmostEquals(location['lat'], 37.4218281, 3)
     self.assertAlmostEquals(location['lng'], -122.0840696, 3)
Esempio n. 2
0
    def main(argv):
        """
        Geocodes a location given on the command line.
        
        Usage:
            googlemaps.py "1600 amphitheatre mountain view ca" [YOUR_API_KEY]
            googlemaps.py 37.4219720,-122.0841430 [YOUR_API_KEY]
            
        When providing a latitude and longitude on the command line, ensure
        they are separated by a comma and no space.
        
        """

        if len(argv) < 2 or len(argv) > 4:
            print main.__doc__
            sys.exit(1)

        query = argv[1]
        if len(argv) == 3:
            api_key = argv[2]
        else:
            api_key = raw_input("Google Maps API key: ")

        gmap = GoogleMaps(api_key)
        try:
            result = gmap.geocode(query)
        except GoogleMapsError, err:
            sys.stderr.write('%s\n%s\nResponse:\n' % (err.url, err))
            json.dump(err.response, sys.stderr, indent=4)
            sys.exit(1)
Esempio n. 3
0
def coords_from_address(address):
    gmaps = GoogleMaps(settings.GOOGLE_API_KEY)
    try:
        result = gmaps.geocode(value)
        lng, lat = result['Placemark'][0]['Point']['coordinates'][0:2]
        return (lat, lng)
    except:
        raise Exception("Address can't be parsed by google maps")
Esempio n. 4
0
def to_address(value, google_api_key, min_accuracy=1):
    if value is None:
        return None
    gmaps = GoogleMaps(google_api_key)
    if isinstance(value, (list, tuple)) and len(value) >= 2:
        if isinstance(value[0], (int, float)) and isinstance(value[1], (int, float)):
            result = gmaps.reverse_geocode(value[0], value[1])
        else:
            result = gmaps.geocode(value[0] + ' near ' + value[1])
    else:
        result = gmaps.geocode(value)
    address = result['Placemark'][0]['address']
    details = result['Placemark'][0]['AddressDetails']
    accuracy = details['Accuracy']
    # Raise an error if the accuracy is insufficient.
    if accuracy < min_accuracy:
        raise GoogleMapsError(602) # unknown address
    country = containers.find(details, 'CountryName', '')
    country_code = containers.find(details, 'CountryNameCode', '')
    state = containers.find(details, 'AdministrativeAreaName', '')
    state_code = containers.find(details, 'AdministrativeAreaNameCode', '')
    locality = containers.find(details, 'LocalityName', '')
    postal_code = containers.find(details, 'PostalCodeNumber', '')
    street_address = containers.find(details, 'ThoroughfareName', '')
    try:
        lng, lat = result['Placemark'][0]['Point']['coordinates'][0:2]
    except:
        lng, lat = None, None
    # Run through some common fixups.
    address_dict = dict(
        country=country,
        country_code=country_code,
        state=state,
        state_code=state_code,
        locality=locality,
        street_address=street_address,
        postal_code=postal_code,
        formatted=address,
        latitude=lat,
        longitude=lng,
    )
    address_fixups(address_dict)
    return address_dict
Esempio n. 5
0
def query_obs(location):
    """
    Query information about a given location.
    
    'CFHT Hawaii'
    'Roque de los muchachos, Canary Islands'
    'Siding Spring, Australia'
    
    """
    
    print "Where the f**k is", location
    gmaps  = GoogleMaps()
    result = gmaps.geocode(location)
    
    pprint.pprint(result['Placemark'][0])
Esempio n. 6
0
def normalize_street_address(raw_address_string):

    gm = GoogleMaps()  # Add API key for premium Google Maps service
    result = None

    try:
        data = gm.geocode(raw_address_string)
        if data is not None:
            result = NormalizedAddress(data)

    except KeyError:
        result = None

    except GoogleMapsError as ex:
        if ex.message != GoogleMapsError.G_GEO_UNKNOWN_ADDRESS:
            raise ex

    return result
Esempio n. 7
0
def normalize_street_address(raw_address_string):

    gm = GoogleMaps() # Add API key for premium Google Maps service
    result = None

    try:
        data = gm.geocode(raw_address_string)
        if data is not None:
            result = NormalizedAddress(data)

    except KeyError:
        result = None

    except GoogleMapsError as ex:
        if ex.message != GoogleMapsError.G_GEO_UNKNOWN_ADDRESS:
            raise ex

    return result
    def test_geocode(self):
        """Test googlemaps geocode() and address_to_latlng()"""

        addr = '1600 amphitheatre mountain view ca'
        gmaps = GoogleMaps(GMAPS_API_KEY)
        result = gmaps.geocode(addr)
        self.assertEqual(result['Status']['code'], 200)
        self.assertEqual(searchkey(result, 'CountryName'), 'USA')
        self.assertEqual(searchkey(result, 'PostalCodeNumber'), '94043')
        self.assertEqual(searchkey(result, 'ThoroughfareName'), '1600 Amphitheatre Pkwy')
        self.assertEqual(searchkey(result, 'LocalityName'), 'Mountain View')
        self.assertEqual(searchkey(result, 'AdministrativeAreaName'), 'CA')
        self.assertEqual(searchkey(result, 'CountryNameCode'), 'US')
        self.assertEqual(searchkey(result, 'address'), '1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA')
        lat, lng = searchkey(result, 'coordinates')[1::-1]
        self.assertAlmostEquals(lat,   37.422125, 3)
        self.assertAlmostEquals(lng, -122.084466, 3)

        (lat2, lng2) = gmaps.address_to_latlng(addr)
        self.assertAlmostEqual(lat, lat2, 3)
        self.assertAlmostEqual(lng2, lng2, 3)
Esempio n. 9
0
    def test_geocode(self):
        """Test googlemaps geocode() and address_to_latlng()"""

        addr = '1600 amphitheatre mountain view ca'
        gmaps = GoogleMaps(GMAPS_API_KEY)
        result = gmaps.geocode(addr)
        self.assertEqual(result['Status']['code'], 200)
        self.assertEqual(searchkey(result, 'CountryName'), 'USA')
        self.assertEqual(searchkey(result, 'PostalCodeNumber'), '94043')
        self.assertEqual(searchkey(result, 'ThoroughfareName'),
                         '1600 Amphitheatre Pkwy')
        self.assertEqual(searchkey(result, 'LocalityName'), 'Mountain View')
        self.assertEqual(searchkey(result, 'AdministrativeAreaName'), 'CA')
        self.assertEqual(searchkey(result, 'CountryNameCode'), 'US')
        self.assertEqual(
            searchkey(result, 'address'),
            '1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA')
        lat, lng = searchkey(result, 'coordinates')[1::-1]
        self.assertAlmostEquals(lat, 37.422125, 3)
        self.assertAlmostEquals(lng, -122.084466, 3)

        (lat2, lng2) = gmaps.address_to_latlng(addr)
        self.assertAlmostEqual(lat, lat2, 3)
        self.assertAlmostEqual(lng2, lng2, 3)
Esempio n. 10
0
#------------------------------------------------------------
# some geocoding with google

import os

#os.system("libreoffice /home/aok/desk/career/cover/2011/DEC/testit.csv")

from time import sleep

import googlemaps
from googlemaps import GoogleMaps
gmaps = GoogleMaps('ABQIAAAA_bTF6jBJCV91-AeK3hTuARRd7SLIw_AFkyDEshsqvmDj9YqyERSyJPS04IT0Kt8XTZL-f3cnhwCI9w')
address = 'Constitution Ave NW & 10th St NW, Washington, DC'
lat, lng = gmaps.address_to_latlng(address)
print lat, lng
result = gmaps.geocode(address)
placemark = result['Placemark'][0]
details = placemark['AddressDetails']['Country']['AdministrativeArea']
zipcode = details['Locality']['PostalCode']['PostalCodeNumber']

#------------------------------------
#the actual program

import csv

import re
import mechanize
#import cookielib
from BeautifulSoup import BeautifulSoup
#import html2text