2

I am very new to leaflet, and I'm trying to workout how to return the lat and lng from a onMapClick event in leaflet to the flask server app, to allow me to use the coordinates t perform a spatial search on my database. The event currently only shows the lat long in a pop-up on the web app.

I've had a search around, but I guess my knowledge is so basic I don't know what functions I'm searching for.

My web map

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" /> <!-- Leaflet CSS file (style sheets)>-->
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script> <!--leaflet java script file>-->

</head>
<body>
    <div id="map1" style="width: 800px; height: 600px;"></div>    
<script>
    var mymap = L.map('map1').setView([51.5, -0.09], 10);

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

    <!--add popups as a layer>-->  
    var popup = L.popup();
    <!--logs the action and gives lat long of where click occured >-->  
    function onMapClick(e) {
        .setLatLng(e.latlng)
        .setContent("You clicked the map at " + e.latlng.toString())
        .openOn(mymap);
    }

    mymap.on('click', onMapClick);
</script>
</body>
</html> 

and the server app

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/demo')
def webMap():
    return render_template('demo.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8090)

EDIT

I have attempted using an ajax call but getting a 405 error

$.ajax('demo/data/', {
      type: 'GET',
      data: {
        lat: e.latlng.lat,
        lng: e.latlng.lng
      }
    });
};

Flask app

@app.route('/demo/data/')
def demoData():
    return request.form['lng'], request.form['lat']
SAB
  • 175
  • 17

1 Answers1

3

A 405 error is a method not allowed error. You should use a POST request sending information when using the REST-api, as discussed here.

You're going to want to change your app.route to,

 @app.route('/demo/data/' methods=["POST"])

To allow a post method

AlexVestin
  • 2,548
  • 2
  • 16
  • 20