def zoom_search(lat, lon): """ search the nearest city by lat and lon """ # generate search areas, nine blocks search grid_lat = round_prec(lat) lats = [grid_lat - grid_size, grid_lat, grid_lat + grid_size] grid_lon = round_prec(lon) lons = [grid_lon - grid_size, grid_lon, grid_lon + grid_size] keys = itertools.product(lats, lons) # find the most suitable key results = [] for key in keys: klat, klon = key city_key = "{0},{1}".format(klat, klon) try: city_list = city_grids[city_key] except KeyError: continue for city in city_list: name, clat, clon = city gcd_error_distance = gcd_dist.calc_dist_degree(clat, clon, lat, lon) results.append((name, gcd_error_distance)) if len(results) > 0: sorted_results = sorted(results, key = lambda k:k[1]) return sorted_results[0] else: return (None, None)
results.append((name, gcd_error_distance)) if len(results) > 0: sorted_results = sorted(results, key = lambda k:k[1]) return sorted_results[0] else: return (None, None) def lookup_city(lat, lon): city, offset_distance = zoom_search(lat, lon) if city: return city else: return None def lookup_coords(city): if city in city_info: lat, lon = city_info[city][:2] return lat, lon else: return None city_info = load_city_info() city_grids = build_city_grids(city_info) if __name__ == "__main__": print zoom_search(44.86503177,-85.51900375) print zoom_search(54.64403, -2.69027) print zoom_search(53.76667, -2.71667) print gcd_dist.calc_dist_degree(54.64403, -2.69027, 53.76667, -2.71667) print zoom_search(4.77742, 7.0134)