Mapbox - 使用 jinja2 传递数据的可视化问题

Mapbox - Visualisation issue with passed data using jinja2

我正在尝试使用 jinja2 将多边形的坐标从我的烧瓶应用程序传递到包含 mapbox gl 的 html。

我的 Flask 应用看起来像这样:

@app.route('/<path:subpath>', methods=['POST', 'GET'])
def show_subpath(subpath):
if request.method == 'POST':
    try:
        data = request.form
        name = 'Eine Karte'
        poly = coords
        return render_template('/map.html', name=name, polygon=poly)
    except:
        return 'That didnt work'

map.html 中包含地图的脚本部分如下所示:

<script>
mapboxgl.accessToken = 'TOKEN';
  var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v9',
  center: [12.940985, 54.063782],
  zoom: 10
});

var geom = '{{ polygon }}';
map.on('load', function() {
  map.addControl(
    new MapboxGeocoder({
        accessToken: mapboxgl.accessToken,
        mapboxgl: mapboxgl
    })
  );
})

map.on('load', function () {
    map.addSource('iso', {
      'type': 'geojson',
      'data': {
        'type': 'Feature',
        'geometry': {
          'type': 'Polygon',
          'coordinates': geom 
        }
      }
    });

    map.addLayer({
     'id': 'iso',
     'type': 'fill',
     // Use "iso" as the data source for this layer
     'source': 'iso',
     'layout': {},
     'paint': {
       // The fill color for the layer is set to a light purple
       'fill-color': '#088',
       'fill-opacity': 0.8
     }
   });
  });
  </script>

当我在脚本末尾使用“console.log(geom)”时,我可以看到数据已正确传递。但是,多边形未显示在地图上。当我对坐标进行硬编码时,它们会出现在地图上。如何可视化传递的数据?

非常简单 - 您将多边形作为 string 传递给 mapbox,而它需要 GeoJSON 对象。我复制了你的代码并得到了

Error {message: "Input data given to 'maine' is not a valid GeoJSON object."}

您想要做的是从您的geom 变量 中删除引号。为了安全起见,您可以使用 tojson 来转义某些字符,这样就不会导致意外错误,尤其是当您在 <script> 标签中使用变量时。

修改var geom = '{{ polygon }}';为:

var geom = {{ polygon|tojson }};

它应该可以工作!

如果你不做任何额外的处理,你也可以删除额外的变量:

map.addSource('maine', {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
// These coordinates outline Maine.
'coordinates':
    {{ polygon|tojson }}
}
}
});

此外,请确保当您从 flask 传递参数时,您没有添加引号以使其成为字符串对象。