Last active
August 29, 2015 14:12
-
-
Save miraculixx/28dea4116594fe74e318 to your computer and use it in GitHub Desktop.
get lat, long of an address from the command line or in Python. Returns a JSON encoded string.
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
# -*- coding: utf-8 -*- | |
# (c) 2014 one2seven GmbH, Switzerland | |
import urllib | |
import json | |
import sys | |
def geocode_by_osm(address): | |
""" | |
geocode an address using openstreet map | |
""" | |
address = address.decode('utf-8') | |
query_address = urllib.quote_plus(address.encode('utf-8')) | |
query_param = "&".join(( | |
'addressdetails=1', | |
'limit=1', | |
'format=json', | |
'q=%s' % query_address, | |
)) | |
request = "http://nominatim.openstreetmap.org/search/?%s" % query_param | |
data = json.loads(urllib.urlopen(request).read()) | |
if len(data) > 0 and 'place_id' in data[0]: | |
place = data[0] | |
return {'query': address, | |
'place': place['display_name'], | |
'lat': place['lat'], | |
'lon': place['lon']} | |
return {} | |
def test(): | |
print geocode_by_osm('Zürich') | |
def main(): | |
if len(sys.argv) == 1: | |
print "Syntax: python geocode.py <place>" | |
exit(1) | |
print json.dumps(geocode_by_osm(sys.argv[1])) | |
if __name__ == '__main__' and "get_ipython" not in dir(): | |
main() | |
if "get_ipython" in dir(): | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
From command line
From within a Python program: