Created
January 9, 2014 04:13
-
-
Save jflatow/8329326 to your computer and use it in GitHub Desktop.
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 collections | |
import json | |
class GeoName(collections.namedtuple('GeoName', | |
['country_code', | |
'postal_code', | |
'place_name', | |
'admin_name_1', 'admin_code_1', | |
'admin_name_2', 'admin_code_2', | |
'admin_name_3', 'admin_code_3', | |
'latitude', 'longitude', | |
'accuracy'])): | |
pass | |
def tile((lat, lng)): | |
return int(lat * 10), int(lng * 10) | |
def box((x, y), w=1): | |
for i in xrange(-w, w + 1): | |
for j in xrange(-w, w + 1): | |
yield x + i, y + j | |
def dist(A, B): | |
return sum((a - b) ** 2 for a, b in zip(A, B)) | |
def parse(filename='allCountries.txt'): | |
with open(filename) as handle: | |
for line in handle: | |
g = GeoName(*line.strip('\n').split('\t')) | |
if g.place_name and g.latitude and g.longitude: | |
yield (float(g.latitude), float(g.longitude)), g.place_name | |
def index(geonames): | |
for latlng, place in geonames: | |
yield '%s,%s' % tile(latlng), json.dumps([latlng, place]) | |
def fetch(point, db): | |
for val in db.get('%s,%s' % point, ()): | |
yield json.loads(val) | |
def query(latlng, db): | |
return sorted((dist(cell[0], latlng), cell) | |
for point in box(tile(latlng)) | |
for cell in fetch(point, db)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment