Geopy – vincenty

In order to find users within a certain radius of another, I used the vincenty method of the geopy module.

from geopy.distance import vincenty

@app.route('/view_players/<string:latitude>/<string:longitude>')
def view_players(latitude, longitude):
    users = User.query.all()
    players = [
        dict_w_dist(user, guest=True, latitude=latitude, longitude=longitude)
        for user in users
        if vincenty(
            (latitude, longitude),
            (user.loc_latitude, user.loc_longitude)
        ).miles < 200
    ]

    sorted_players = sorted(
        players, 
        key=itemgetter('dist_apart'), 
        reverse=False
    ) 
    return render_template(
        "find.html", 
        players=sorted_players, 
        state="find", 
        name="Guest"
    )

def dict_w_dist(query_obj, guest=False, latitude=None, longitude=None):
    query_dict = query_obj.__dict__
    del query_dict['_sa_instance_state']
    if guest == True:
        query_dict['dist_apart'] = vincenty(
            (latitude, longitude),
            (query_dict["loc_latitude"], query_dict["loc_longitude"])
        ).miles
        query_dict['name'] = query_dict['name'][:1] + '.'
    else:
        query_dict['dist_apart'] = vincenty(
            (g.user.loc_latitude, g.user.loc_longitude),
            (query_dict["loc_latitude"], query_dict["loc_longitude"])
        ).miles 
    return query_dict

When a guest player tries to view other players in the area, first all the users are queried from the database and returned as a ‘users’ object. Then a new list is created by passing each user and passing it into the dict_w_dist function, which returns user as a dictionary and adds the attribute ‘dist_apart’ from the active user and the queried user.

In this example, users are included into the players list if the distance is less than 200 miles. The list is then sorted by distance apart and sent as a variable when the template is rendered.

Full code for project here.