使用Flask将坐标从Leaflet传递到Sqlite数据库

时间:2018-07-21 21:41:06

标签: python sqlite flask leaflet flask-sqlalchemy

在我的Flask应用程序上,当用户单击Leaflet地图时,我希望将已单击的位置的位置发送到我的Sqlite数据库中。

map.html如下:

<!DOCTYPE html>
<html>
<head>

    <title>Quick Start - Leaflet</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>



</head>
<body>


<div>
    <div id="mapid" style="width: 600px; height: 400px; margin-left: 500px"></div>
    <script>

        var mymap = L.map('mapid').setView([51.505, -0.09], 13);

        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
            maxZoom: 18,
            attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
                '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
                'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
            id: 'mapbox.streets'
        }).addTo(mymap);

        L.marker([51.5, -0.09]).addTo(mymap)
            .bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();



        var popup = L.popup();

        function onMapClick(e) {
            var marker = new L.marker(e.latlng).addTo(mymap);
            var data = {'lat': e.latlng.lat,
                        'lng': e.latlng.lng}
            console.log(e.latlng)
            $.ajax({
            url: Flask.url_for('map_'),
            type: 'POST',
            data: JSON.stringify(data),   // converts js value to JSON string
            })
            .done(function(result){     // on success get the return object from server
                console.log(result)     // do whatever with it. In this case see it in console
            }
            popup
                .setLatLng(e.latlng)
                .setContent("You clicked the map at " + e.latlng.toString())
                .openOn(mymap);
        }

        mymap.on('click', onMapClick);

    </script>
</div>

</body>
</html>

烧瓶路线如下:

@main.route("/map" , methods=['GET', 'POST'])
def map_():
    if request.method == "POST":
        data ={}
        data['lat'] = request.form['lat']
        data['lng'] = request.form['lng']
        cords = Map(lat=data['lat'], lng=data['lng'])
        db.session.add(cords)
        db.session.commit()
        flash('Your location has been stored!', 'success')
        return redirect(url_for('main.home'))
    return render_template('map.html', title='Map')

地图功能如下:

class Map(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    lat = db.Column(db.Float)
    lng = db.Column(db.Float)


    def __repr__(self):
        return "Map('{}', '{}')".format(self.lat, self.lng)

因此,为了使其更清楚一点,我可以在地图上留下显示我的坐标的标记,但是无法将其提交到数据库中。当我运行该应用程序时,绝对没有错误消息,因此希望你们中的一些人可以帮助我。

0 个答案:

没有答案