Search code examples
javascriptpythonpython-3.xflaskgeolocation

Using JS Geolocation in Flask Web App (Python 3.6.6)


I'm working on a web app in Flask using Heroku, and am trying to incorporate latitude and longitude data into the app (I want to take the user's current lat/lon from my login.html file and compare it to a pre-specified lat/lon in my application.py file). I have the JS component of the code written, but I'm not sure what to do with it - how do I take the geolocation data from JS and use it in Flask? Also, how might I be able to see the user's current lat/lon?

Any help on this is much, much appreciated. JS Code:

{% extends "layout.html" %}

{% block title %}
    Log In
{% endblock %}

{% block main %}
    <form action="/login" method="post">
        <div class="form-group">
            <input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"/>
        </div>
        <div class="form-group">
            <input class="form-control" name="password" placeholder="Password" type="password"/>
        </div>
        <button class="btn btn-primary" type="submit">Log In</button>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript">// <![CDATA[
        //run this code when the page loads
        jQuery(document).ready(function(){  
            //call the getGeolocation function below
            getGeolocation();
        });  
        //determine if the user's browser has location services enabled. If not, show a message
        function getGeolocation() { 
            if(navigator.geolocation){
                //if location services are turned on, continue and call the getUserCoordinates function below
                 navigator.geolocation.getCurrentPosition(getUserCoodinates);  
            }else{
                alert('You must enable your device\'s location services in order to run this application.');
            }
        }  
        //function is passed a position object which contains the lat and long value
        function getUserCoodinates(position){  
            //set the application's text inputs LAT and LONG = to the user's lat and long position
            jQuery("#LAT").val(position.coords.latitude);
            jQuery("#LONG").val(position.coords.longitude);
        }
    // ]]></script>
{% endblock %}

Solution

  • How about using ajax? You might need an ajax function in your JS. I searched all related articles on SO for you and I think you can apply this. I verified it works. Hope it helps :)