Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miraculixx/28dea4116594fe74e318 to your computer and use it in GitHub Desktop.
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.
# -*- 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()
@miraculixx
Copy link
Author

Example

From command line

$ python geocode.py Basel, Bahnhof
{"lat": "47.5581077", "query": "Basel,", "place": "Basel, Basel-Stadt, Schweiz, Suisse, Svizzera, Svizra", "lon": "7.5878261"}

From within a Python program:

from geocode import geocode_by_osm 

place = 'Basel'
coded = geocode_by_osm(place)
lat, long = coded.get('lat'), coded.get('lon')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment