def search_radius(search_center_string, postalcodes, radius): """ Finds zipcodes in the database that are within a search radius of a location. This uses the python library geolocation-python, which uses the GoogleMaps API. Takes in search center as a string, postalcodes as a list of tuples (because that is the format returned from the database), and search radius in miles as an integer. The function returns the list of postal codes in the given list that are within the given radius. """ search_center_int = int(search_center_string) print "\n\n\n\n**********SEARCH CENTER INT IS: %d*************\n\n\n\n" % search_center_int # Check if zipcode is in database. If not, get lat and long from # GoogleMaps and add it to the database. ############# TODO: WHY IS THIS NOT MAKING A NEW POSTALCODE OBJECT????? ##### search_center_obj = PostalCode.query.get(search_center_int) if not search_center_obj: make_postalcode(search_center_string) search_center_obj = PostalCode.query.get(search_center_int) print "************Search center object: \n\n\n\n %r \n\n\n\n**************" % search_center_obj # SQLite returns the distinct postal codes as a list of tuples. Convert this # to a list of postal code strings. postalcodes_in_db = [] for postalcode in postalcodes: postalcodes_in_db.append(postalcode[0]) postalcodes_within_radius = [] lat1 = search_center_obj.latitude lng1 = search_center_obj.longitude for postalcode in postalcodes_in_db: location = PostalCode.query.get(int(postalcode)) lat2 = location.latitude lng2 = location.longitude distance = calc_Haversine_distance(lat1, lng1, lat2, lng2) if distance <= radius: postalcodes_within_radius.append(postalcode) return postalcodes_within_radius
def test_make_postalcode(self): make_postalcode('98570') a = PostalCode.query.get(98570) self.assertEqual(int(a.latitude), 46) self.assertEqual(int(a.longitude), -122)