简体   繁体   English

如何将带有Flask的GeoJSON返回给Openlayers

[英]How to return GeoJSON with Flask to Openlayers

I have a simple flask function that renders a template with a valid GeoJSON string: 我有一个简单的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)

In my json.html file, I am attempting to render this GeoJSON with OpenLayers: 在我的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));

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 我确实忘了将json转储到实际的字符串中,我使用的是geojson库,因此添加了功能

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 可以解决这个问题,但是根据geojsonlint.com,即使它是有效的字符串,我仍然无法在OpenLayers中解析GeoJSON。

This is the Javascript code to create a variable from the string sent from flask: 这是Java代码,用于从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. 我仍然在呈现引号字符时遇到问题。

Look like you use shapely which has http://toblerity.org/shapely/shapely.geometry.html#shapely.geometry.mapping method to create GeoJSON -like object. 看起来像你使用shapely其中有http://toblerity.org/shapely/shapely.geometry.html#shapely.geometry.mapping方法来创建GeoJSON状物体。

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. 要渲染json使用tojson过滤器,该过滤器对于最新的flask版本而言是安全的(请参阅safe过滤器),因为默认情况下, flaskjinja2转义所有危险符号以保护XSS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM