如何使用Flask向Openlayers返回GeoJSON

3

我有一个简单的flask函数,它使用有效的GeoJSON字符串呈现模板:

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

在我的json.html文件中,我正试图使用OpenLayers呈现这个GeoJSON:
 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));

但这种方法失败了,双引号字符变成了单引号。我尝试过像这个问题中看到的字符串格式化方法question,但它没有起作用。
编辑:
我忘记将我的json转换为实际的字符串了,我正在使用geojson库,所以添加该函数。
dumps(polygon)

这个问题已经得到解决,但是我仍然无法在 OpenLayers 中解析 GeoJSON,即使它是根据 geojsonlint.com 验证的有效字符串。

以下是用于从 Flask 发送的字符串创建变量的 JavaScript 代码:

var geoJson = '{{string}}';

这是在源页面中的样子:
'{"type": "Polygon", "coordinates": [[[22.739485934746977, 39.26596659794341], [22.73902517923571, 39.266115931275074], [22.738329551588276, 39.26493626464484], [22.738796023230854, 39.26477459496181], [22.739485934746977, 39.26596659794341]]]}';

我仍然遇到渲染引号字符的问题。
1个回答

1

那是问题的一部分,但还没有到位,看看我的编辑。 - camdenl
所有工作都正常,jinja2默认转义危险符号以保护XSS。要插入安全标记,您应该使用safe过滤器将模板变量标记为安全(请参见{{ string|safe }}),但是对于JSON最好使用特殊的tojson过滤器,它也是安全的(至少适用于最新的Flask版本),并且等同于{{ flask.json.dupms(polygon)|safe }}(请参见{{ string|tojson }})。 - tbicr
这是正确的答案,您可以将其添加到您的答案文本中吗? - camdenl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接