Django-如何在Mapbox地图上显示GeoJSON?

时间:2019-02-26 17:02:29

标签: javascript django mapbox

我正在使用Django(v1.11)和Mapbox,显示包含一些GeoJSON内容的地图,这些内容是从本地文件加载的。例如,我正在使用this sample.json file

我的想法是将GeoJSON文件加载到JSON对象中,然后将其传递给模板(在本例中为 map.html )。此外,我尝试将JSON对象转换为字符串,传递该字符串,然后使用Javascript重新创建一个新的JSON对象(如下所示)。两种方法都不适合我。

但是,如果我只是将 sample.json 的内容复制并粘贴为Javascript变量,则一切正常,并且GeoJSON可以正确显示。

所以我的问题是,如何从文件加载GeoJSON,将其传递给HTML模板,然后在Mapbox地图上显示内容?

views.py

def get(self, request, *args, **kwargs):
    with open('/somepath/sample.json') as f:
        data = json.load(f)
    data = json.dumps(data)
    return render(request, 'map.html', {'data':data})

map.html

map.on('load', function () {

    // THIS DOES NOT WORK

    var json_data = JSON.parse({{ data }})

    map.addLayer({
        'id': 'layerid',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': json_data
        }
    });
});

map.html

map.on('load', function () {

    // THIS WORKS

    var json_data = { "type": "FeatureCollection",
    "features": [
      { "type": "Feature",
        "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
        "properties": {"prop0": "value0"}
        },
      { "type": "Feature",
        "geometry": {
          "type": "LineString",
          "coordinates": [
            [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]
            ]
          },
        "properties": {
          "prop0": "value0",
          "prop1": 0.0
          }
        },
      { "type": "Feature",
         "geometry": {
           "type": "Polygon",
           "coordinates": [
             [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0],
               [100.0, 1.0], [100.0, 0.0] ]
             ]
         },
         "properties": {
           "prop0": "value0",
           "prop1": {"this": "that"}
           }
         }
      ]
    }

    map.addLayer({
        'id': 'layerid',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': json_data
        }
    });
});

编辑

我现在也尝试过:

views.py

def get(self, request, *args, **kwargs):
    return render(request, 'map.html', {'path':'/somepath/sample.json'})

map.html

map.on('load', function () {

    // THIS DOES NOT WORK

    $.getJSON({{ path }}, function(data) {
        var json_data = data
    });

    map.addLayer({
        'id': 'layerid',
        'type': 'fill',
        'source': {
            'type': 'geojson',
            'data': json_data
        }
    });
});

0 个答案:

没有答案
相关问题