def get_nearby_checkpoints(user_obj, point_coord, radius_in_kilometres): """ get UserCheckpoints in a given radius sorted according to proximity returns in tuple, (friends_user_checkpoints_list, anonymous_user_checkpoints_list) """ from db import UserCheckpoint, db, Checkpoint #bounding box lat, lon = point_coord[0], point_coord[1] dlat, dlon = bounding_box(lat, lon, radius_in_kilometres) min_lat, max_lat = lat-dlat, lat+dlat min_lon, max_lon = lon-dlon, lon+dlon radius_cond = and_(Checkpoint.latitude <= max_lat, Checkpoint.latitude >= min_lat, Checkpoint.longitude <= max_lon, Checkpoint.longitude >= min_lon ) ucp_in_radius = (db.session.query(UserCheckpoint). join(UserCheckpoint.checkpoint). filter(radius_cond). filter(Checkpoint.demo == False) ) #removing dupes and making sure that the oldest creator always gets credited unduped_ucp = {} all_ucp = ucp_in_radius.all() for ucp in all_ucp: key = ucp.checkpoint.id if key in unduped_ucp: compared_ucp = unduped_ucp[key] if ucp.user_id == user_obj.id: unduped_ucp[key] = ucp elif ucp < compared_ucp and compared_ucp.user_id != user_obj.id: #older unduped_ucp[key] = ucp else: unduped_ucp[key] = ucp all_ucp = [v for k,v in unduped_ucp.iteritems()] ucp_namedtuples = _checkpoints_to_location_namedtuples(all_ucp) sorted_ucp = proximity_sort((lat, lon), ucp_namedtuples, ucp_in_radius.count()) #separate into friends and anon ucp friend_list = get_friends(user_obj) friends = [] anon = [] for ucp in sorted_ucp: if ucp.user_checkpoint.user in friend_list: friends += [ucp.user_checkpoint] else: anon += [ucp.user_checkpoint] return friends, anon
def sort_checkpoints(ucp_lis, sort_method, **kwargs): """ sorts checkpoints according to method supplied. methods available are: newest, nearest, popular if "nearest" method is chosen, longitude/latitude kw args should be provided. """ sorted_ucp = None if sort_method == "popular": sorted_ucp = sorted(ucp_lis, key=lambda ucp: get_total_likes(ucp), reverse=True) elif sort_method == "nearest": lat, lon = kwargs["latitude"], kwargs["longitude"] ucp_namedtuples = _checkpoints_to_location_namedtuples(ucp_lis) sorted_ucp = proximity_sort((lat, lon), ucp_namedtuples, len(ucp_namedtuples)) sorted_ucp = [ucp[1] for ucp in sorted_ucp] else: #newest sorted_ucp = sorted(ucp_lis, key=lambda ucp: ucp.checkpoint.date_created, reverse=True) return sorted_ucp