-
-
Save danstowell/3923307 to your computer and use it in GitHub Desktop.
simplified version of reverse geocode parse
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
#!/bin/env python | |
# python port by Dan Stowell, of OSM reverse geocoding by Tom Morris | |
import json | |
import urllib2 | |
def latlon_to_label(latitude, longitude): | |
url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=%f&lon=%f&zoom=18&addressdetails=1" % (latitude, longitude) | |
data = urllib2.urlopen(url).read() | |
result = json.loads(data) | |
result_arr = [] | |
# london mode | |
if u"state_district" in result[u"address"] and result[u"address"][u"state_district"] == u"Greater London": | |
if u"place" in result[u"address"]: | |
result_arr.append(result[u"address"][u"place"]) | |
else: | |
if u"pedestrian" in result[u"address"]: | |
result_arr.append(result[u"address"][u"pedestrian"]) | |
elif u"footway" in result[u"address"]: | |
result_arr.append(result[u"address"][u"footway"]) | |
if u"suburb" in result[u"address"]: | |
result_arr.append(result[u"address"][u"suburb"]) | |
# county should be 'London' :) | |
if u"county" in result[u"address"]: | |
result_arr.append(result[u"address"][u"county"]) | |
# strip end off postcodes | |
if u"postcode" in result[u"address"]: | |
postcode = result[u"address"][u"postcode"] | |
if len(postcode.split(u" ")) != 1: | |
result_arr.append(postcode.split(u" ")[0]) | |
else: | |
result_arr.append(postcode) | |
# not london. | |
else: | |
if u"road" in result[u"address"]: | |
result_arr.append(result[u"address"][u"road"]) | |
if u"suburb" in result[u"address"]: | |
result_arr.append(result[u"address"][u"suburb"]) | |
if u"town" in result[u"address"]: | |
result_arr.append(result[u"address"][u"town"]) | |
else: | |
if u"city" in result[u"address"]: | |
result_arr.append(result[u"address"][u"city"]) | |
return u", ".join(result_arr) | |
if __name__ == '__main__': | |
print "These examples should match:" | |
tocheck = [(u"St Pancras, London, NW1", 51.5294418333333,-0.126272633333333), | |
(u"St Pancras, London, NW1", 51.5295385,-0.1264996), | |
(u"Bishops Square, London, E1", 51.5192044,-0.077819), | |
(u"Westminster, London, WC2N", 51.509092275,-0.123459925), | |
(u"Gloucester Road, Round Hill, Brighton", 50.8267737,-0.1367264), | |
(u"Trinity Street, Bohemia, Hastings", 50.8550399,0.5767676), | |
] | |
for (string, lat, lon) in tocheck: | |
result = latlon_to_label(lat, lon) | |
if string == result: | |
print "OK: %s" % string | |
else: | |
raise ValueError("%s != %s" % (string, result)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment