-
-
Save zdwolfe/d06a9392cda90012e07f30dbc7022919 to your computer and use it in GitHub Desktop.
geocoding sandbox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib.request | |
import urllib.parse | |
import json | |
import os | |
class LocationService: | |
def get_lat_lon(self, campsite_name): | |
pass | |
class OpenStreetMap(LocationService): | |
def get_lat_lon(self, campsite_name): | |
base_url = "https://nominatim.openstreetmap.org/search" | |
params = { | |
'q': campsite_name, | |
'format': 'json' | |
} | |
url = base_url + "?" + urllib.parse.urlencode(params) | |
with urllib.request.urlopen(url) as response: | |
data = json.loads(response.read().decode()) | |
if data: | |
latitude = data[0]['lat'] | |
longitude = data[0]['lon'] | |
return latitude, longitude | |
else: | |
return None, None | |
class GoogleMaps(LocationService): | |
def __init__(self, api_key): | |
self.api_key = api_key | |
def get_lat_lon(self, campsite_name): | |
base_url = "https://maps.googleapis.com/maps/api/geocode/json" | |
params = { | |
'address': campsite_name, | |
'key': self.api_key | |
} | |
url = base_url + "?" + urllib.parse.urlencode(params) | |
with urllib.request.urlopen(url) as response: | |
data = json.loads(response.read().decode()) | |
if data['results']: | |
location = data['results'][0]['geometry']['location'] | |
return location['lat'], location['lng'] | |
else: | |
return None, None | |
class BingMaps(LocationService): | |
def __init__(self, api_key): | |
self.api_key = api_key | |
def get_lat_lon(self, campsite_name): | |
base_url = "http://dev.virtualearth.net/REST/v1/Locations" | |
params = { | |
'q': campsite_name, | |
'key': self.api_key | |
} | |
url = base_url + "?" + urllib.parse.urlencode(params) | |
with urllib.request.urlopen(url) as response: | |
data = json.loads(response.read().decode()) | |
if data['resourceSets'] and data['resourceSets'][0]['resources']: | |
location = data['resourceSets'][0]['resources'][0]['point']['coordinates'] | |
return location[0], location[1] | |
else: | |
return None, None | |
campsite_name = "Silver Falls Group Site Okanogan-Wenatchee National Forest, WA" | |
osm = OpenStreetMap() | |
lat, lon = osm.get_lat_lon(campsite_name) | |
print(f"Latitude: {lat}, Longitude: {lon}") | |
if (os.environ.get('GMAPS_KEY')): | |
gmaps = GoogleMaps(os.environ.get('GMAPS_KEY')) | |
lat, lon = gmaps.get_lat_lon(campsite_name) | |
print(f"Latitude: {lat}, Longitude: {lon}") | |
if (os.environ.get('BINGMAPS_KEY')): | |
bmaps = BingMaps(os.environ.get('BINGMAPS_KEY')) | |
lat, lon = bmaps.get_lat_lon(campsite_name) | |
print(f"Latitude: {lat}, Longitude: {lon}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment