Geopy – Nominatim

I used the Geopy.geocoders module to standardize location information into latitude/longitude for my ItsPong project.

from geopy.geocoders import Nominatim

@app.route('/set_location', methods=['GET', 'POST'])
@app.route('/set_location/<string:set_type>', methods=['GET', 'POST'])
@login_required
def set_location(set_type=None):
    user = User.query.filter_by(id=g.user.id).first()

    if request.method == 'POST':
        input_location = request.form['address']
        geolocator = Nominatim()
        try:
            location = geolocator.geocode(input_location)
            user.loc_input = input_location
            user.loc_latitude = location.latitude
            user.loc_longitude = location.longitude
            db.session.commit()
        except:
            location = None
        return render_template(
            'set_location.html', 
            location=location, 
            type=set_type
        )

    if set_type:
        loc_input = user.loc_input
    else:
        loc_input = None
    return render_template(
        'set_location.html', 
        type=set_type, 
        current_loc=loc_input
    )

When the user submits the location information via a ‘POST’ method, a geolocator object is created using the Nominatim constructor from the geopy.geocoders module. A location object is created which contains latitude and longitude coordinates. If there is no error, this information is saved for the user. If there is an error, the template is re-rendered and a message asking for a valid location appears.

Link to github here.