|
| 1 | + |
| 2 | +# Michael Galarnyk |
| 3 | +# Assignment 7 |
| 4 | + |
| 5 | +# “Google Geocoding” |
| 6 | +# 1. Change either the geojson.py or geoxml.py program to print out the two-character country code from the retrieved data. |
| 7 | +# 2. Add error checking so your program does not traceback if the country code is not there. |
| 8 | +# 3. Use the program to search for “Pacific Ocean” and make sure that it can handle locations that |
| 9 | +# are not in any country. |
| 10 | + |
| 11 | +import urllib |
| 12 | +import json |
| 13 | + |
| 14 | +serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?' |
| 15 | + |
| 16 | +while True: |
| 17 | + address = raw_input('Enter location: ') |
| 18 | + if len(address) < 1 : break |
| 19 | + |
| 20 | + url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address}) |
| 21 | + print 'Retrieving', url |
| 22 | + uh = urllib.urlopen(url) |
| 23 | + data = uh.read() |
| 24 | + print 'Retrieved',len(data),'characters' |
| 25 | + |
| 26 | + try: js = json.loads(str(data)) |
| 27 | + except: js = None |
| 28 | + if 'status' not in js or js['status'] != 'OK': |
| 29 | + print '==== Failure To Retrieve ====' |
| 30 | + print data |
| 31 | + continue |
| 32 | + |
| 33 | + print json.dumps(js, indent=4) |
| 34 | + ''' |
| 35 | + lat = js["results"][0]["geometry"]["location"]["lat"] |
| 36 | + lng = js["results"][0]["geometry"]["location"]["lng"] |
| 37 | + print 'lat',lat,'lng',lng |
| 38 | + ''' #not necessary for this assignment |
| 39 | + location = js['results'][0]['formatted_address'] |
| 40 | + print location |
| 41 | + |
| 42 | + results = js['results'][0] |
| 43 | + address_components = results["address_components"] |
| 44 | + country = 0; |
| 45 | + for each_dict in address_components: |
| 46 | + types = each_dict["types"] |
| 47 | + if types == ["country", "political"]: |
| 48 | + country = 1; |
| 49 | + print "The two character country code is:", each_dict["short_name"] |
| 50 | + |
| 51 | + if country == 0: |
| 52 | + print "Location isn't in any country" |
0 commit comments