How to Build a Geolocation App Using Flask

How to Build a Geolocation App Using Flask

Introduction

Install modules

To install the above-mentioned modules enter the commands below on your terminal as shown below.

pip3 install Flask

pip3 install geopy

Project Structure

Create a folder called flask-location and inside it create a folder called templates and create a file called index.html . Now inside the flask-location folder create a file called app.py.

Import modules

Inside the app.py file created earlier import the following modules and finally initialize the application as shown below.

from flask import Flask,request, render_template

from geopy.geocoders import Nominatim

app = Flask(__name__)

Create view

Now let’s create the view to handle our application logic.


@app.route('/', methods=['POST'])
def get_location():
    # get the location from the form
    address = request.form['address']

    # create a geolocator object
    geolocator = Nominatim(user_agent="bytexplain")

    # get the location of the address
    location = geolocator.geocode(address)

    # render the template with the location data
    return render_template('index.html', location=location)

if __name__ == '__main__':
    app.run(debug=True)

Create template

Inside the index.html file we created earlier insert the code below.

<!DOCTYPE html>
<html>
<head>
    <title>Geolocation App</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <h1 style="text-align : center";>Geolocation App</h1>
        <form method="POST">
            <div class="form-group">
                <input type="text" class="form-control" id="address" name="address" placeholder="Enter an address">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>

        {% if location %}
        <div class="text-center">
            <h2>Coordinates:</h2>
            <p>Latitude: {{ location.latitude }}</p>
            <p>Longitude: {{ location.longitude }}</p>
        </div>
        {% endif %}
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

Run

Open your terminal and run the command below to start the server.

python3 app.py

Results

After the command above runs successfully our application should be available in the browser at the address [ http://127.0.0.1:5000 ] as shown below.

There you have it, Thanks for reading. Happy coding.

Leave a Comment

Your email address will not be published. Required fields are marked *