Search code examples
pythonjsonflaskopenlayersgeojson

How to return GeoJSON with Flask to Openlayers


I have a simple flask function that renders a template with a valid GeoJSON string:

@app.route('/json', methods=['POST'])
def json():    
    polygon = Polygon([[[0,1],[1,0],[0,0],[0,1]]])
    return render_template('json.html',string=polygon)

In my json.html file, I am attempting to render this GeoJSON with OpenLayers:

 function init(){
            map = new OpenLayers.Map( 'map' );
            layer = new OpenLayers.Layer.WMS( "OpenLayers WMS", 
                    "http://vmap0.tiles.osgeo.org/wms/vmap0",
                    {layers: 'basic'} );
            map.addLayer(layer);
            map.setCenter(new OpenLayers.LonLat(lon, lat), zoom);
            var fc = {{string}};        //Here is the JSON string
            var geojson_format = new OpenLayers.Format.GeoJSON();
            var vector_layer = new OpenLayers.Layer.Vector(); 
            map.addLayer(vector_layer);
            vector_layer.addFeatures(geojson_format.read(fc));

But this fails and the " characters become '. I have tried string formatting as seen in this question, but it didn't work.

EDIT:

I did forget to dump my json to an actual string, I'm using the geojson library so adding the function

dumps(polygon)

takes care of that, however I still can't parse the GeoJSON in OpenLayers, even though it is a valid string according to geojsonlint.com

This is the Javascript code to create a variable from the string sent from flask:

var geoJson = '{{string}}';

And here's what it looks like in the source page:

'{"type": "Polygon", "coordinates": [[[22.739485934746977, 39.26596659794341], [22.73902517923571, 39.266115931275074], [22.738329551588276, 39.26493626464484], [22.738796023230854, 39.26477459496181], [22.739485934746977, 39.26596659794341]]]}';

I am still having a problem rendering the quote characters.


Solution

  • Look like you use shapely which has http://toblerity.org/shapely/shapely.geometry.html#shapely.geometry.mapping method to create GeoJSON-like object.

    To render json use tojson filter which safe (see safe filter) for latest flask versions, because jinja2 in flask by default escape all dangerous symbols to protect XSS.