首页 > 解决方案 > 在 Flask Web App (Python 3.6.6) 中使用 JS 地理定位

问题描述

我正在使用 Heroku 在 Flask 中开发一个网络应用程序,并试图将纬度和经度数据合并到应用程序中(我想从我的 login.html 文件中获取用户当前的纬度/经度并将其与预先指定的我的 application.py 文件中的纬度/经度)。我编写了代码的 JS 组件,但我不确定如何处理它 - 如何从 JS 获取地理位置数据并在 Flask 中使用它?另外,我怎样才能看到用户当前的纬度/经度?

对此的任何帮助都非常非常感谢。JS代码:

{% 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 %}

标签: javascriptpythonpython-3.xflaskgeolocation

解决方案


使用ajax怎么样?你的 JS 中可能需要一个 ajax 函数。我为你搜索了所有关于 SO 的相关文章,我认为你可以应用。我验证它有效。希望能帮助到你 :)


推荐阅读