Skip to content

Instantly share code, notes, and snippets.

@CloudCray
Last active August 29, 2015 14:02
Show Gist options
  • Save CloudCray/eaa80df249afdb02bf8a to your computer and use it in GitHub Desktop.
Save CloudCray/eaa80df249afdb02bf8a to your computer and use it in GitHub Desktop.
Geocoding with Google Geocoding API
# Keep in mind, google has some strict policy on usage (2,500 per day from any IP address)
# Python 3
# Also see the API docs:
# https://developers.google.com/maps/documentation/geocoding/
import urllib.request
import urllib.parse
import json
url = r"http://maps.googleapis.com/maps/api/geocode/json?"
record = {"address": "1600 Pennsylvania Ave NW, Washington, DC 20500"} # White House
params = urllib.parse.urlencode(record)
url_params = url + params
req = urllib.request.Request(url_params)
resp = urllib.request.urlopen(req)
text = resp.read().decode("ascii", "ignore")
result = json.loads(text)
print(text)
print("Latitude: " + str(result["results"][0]["geometry"]["location"]["lat"]))
print("Longitude: " + str(result["results"][0]["geometry"]["location"]["lng"]))
"""
# The resutls for the White House data:
{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "President's Park",
"short_name" : "President's Park",
"types" : [ "establishment" ]
},
{
"long_name" : "Pennsylvania Avenue Northwest",
"short_name" : "Pennsylvania Ave NW",
"types" : [ "route" ]
},
{
"long_name" : "Washington",
"short_name" : "Washington",
"types" : [ "locality", "political" ]
},
{
"long_name" : "District of Columbia",
"short_name" : "DC",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "20500",
"short_name" : "20500",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Pennsylvania Avenue Northwest, President's Park, Washington, DC 20500, USA",
"geometry" : {
"location" : {
"lat" : 38.8978378,
"lng" : -77.0365123
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 38.89918678029149,
"lng" : -77.03516331970849
},
"southwest" : {
"lat" : 38.89648881970849,
"lng" : -77.03786128029151
}
}
},
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
Latitude: 38.8978378
Longitude: -77.0365123
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment