1

I have a small flask app I am using it to:

  • Make an HTML page with a leaflet map
  • Take user input from the HTML page...
  • Run calculations on that input using certain python modules
  • Return those variable to JS functions in the page to populate the map

I cannot get ANYTHING but lat and lng to return into my HTML {{}} flask variables.

Here is my HTML page:

<!DOCTYPE html>
<html lang="en">
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"
     integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
     crossorigin=""/>
     <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"
  integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
  crossorigin="">
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
    <meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>


<body>

<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
 <br/>
 <button>Get data</button>
 </form>

{% if lat1 != None and lng1 != None %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}

{% if point != None %}
<p>{{point}}</p>
{% endif %}

{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}

<div id="mapid"></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={accessToken}', {
     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>',
     maxZoom: 18,
     id: 'mapbox.high-contrast',
     accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
    }).addTo(mymap);

    function zoomTo() {
    mymap.panTo(new L.LatLng(lat1, lng1));
                      }

    function addGJ(){
      var myLayer = L.geoJson(GeJ).addTo(mymap);
                    }
    window.onload = zoomTo();
    window.onload = addGJ();
     </script>
</body>
</html>

Here is my Flask Python code:

from flask import Flask, render_template, request, flash, redirect, url_for,jsonify
from forms import RegistrationForm
import json
import osmnx as ox
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import json_graph
import pandas as pd
import mplleaflet
app = Flask(__name__)

app.config.update(dict(
    SECRET_KEY="powerful secretkey",
    WTF_CSRF_SECRET_KEY="a csrf secret key"
))
@app.route('/')
def my_form():
    return render_template('map.html')

@app.route('/', methods=['GET', 'POST'])
def my_form_post():
    lat = (request.form['lat'])
    lng = (request.form['lng'])
    lat = lat
    lng = lng
    point = (lat,lng)
    G = ox.core.graph_from_point(point, distance = 500, network_type='walk')
    fig, ax = ox.plot_graph(G)
    GJ = mplleaflet.fig_to_geojson(fig=ax.figure)
    #return lat, ",", lng
    return render_template('map.html', lat1=lat, lng1=lng, GeJ=GJ, point="test_string")`



if __name__ == "__main__":
    app.run(host='0.0.0.0',port=5000,debug=True)

The Flask app is working fine so the file structure is not a concern. I just cannot get any other variables to return into my HTML. I even tried making little string dummy variables other that the real ones. No Dice.

Thanks

clayton groth
  • 199
  • 2
  • 16
  • I'm not really sure what you're asking. You're only passing lat1, lng1 and GeJ to your template, you're not passing point. – Daniel Roseman Jun 14 '18 at 19:09
  • I've tried passing it as well with no results. I'll update my code to reflect that. Regardless, GeJ won't show either. – clayton groth Jun 14 '18 at 19:11
  • Have you tried just rendering {{GeJ}} outside of the script tags, what does the HTML show? Are your fucntions generating JSON responses or the actual JSON string format? – Attack68 Jun 14 '18 at 19:43
  • agree with @Daniel Roseman - your code does not show the problem that you are describing: you pass several variables in to `render_template()`, what is going wrong afterwards? Perhaps a comment inside the code can help. – Evgeny Jun 14 '18 at 20:45

3 Answers3

1

You could try using the builtin none value http://jinja.pocoo.org/docs/templates/#none

Then do something like:

{% if lat1 is not none and lng1 is not none %}
Alec1017
  • 119
  • 6
1

<!DOCTYPE html>
<html lang="en">
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"
     integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
     crossorigin=""/>
     <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"
  integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
  crossorigin="">
    </script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
    <meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>


<body>

<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
 <br/>
 <button>Get data</button>
 </form>

{% if lat1 is not Null and lng1 is not Null %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}

{% if point != None %}
<p>{{point}}</p>
{% endif %}

{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}

<div id="mapid"></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={accessToken}', {
     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>',
     maxZoom: 18,
     id: 'mapbox.high-contrast',
     accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
    }).addTo(mymap);

    function zoomTo() {
    mymap.panTo(new L.LatLng(lat1, lng1));
                      }

    function addGJ(){
      var myLayer = L.geoJson(GeJ).addTo(mymap);
                    }
    window.onload = zoomTo();
    window.onload = addGJ();
     </script>
</body>
</html>
Ayoub Benayache
  • 1,046
  • 12
  • 28
1

It would help if you provided an example of what exactly happens when you pass all the values.

Otherwise, what according to me, could be causing the problem is that the 'Null' object in python is the singleton None. The best way to check things for "Noneness" is to use is not None or better still, something as simple as:

{%if lat%} {{lat}} {% endif %}

Also, can't you assign GeJ to the var GeJ within the div instead of putting a line of JS in an abrupt manner up there?

P.S. I wanted to add this as a comment, but don't have enough reputation. Apologies.