如何将geojson文件的内容分配给Javascript中的变量?

时间:2019-05-03 09:11:35

标签: javascript geojson mapbox-gl-js

显示的代码已经可以使用,但是我想清理它。它声明了一个名为 placez 的变量,该变量包含geojson格式的信息,以便下一部分代码可以使用过滤器读取和加载到地图上。但是,实际上,要映射的点数超过50,000(此处的示例仅显示2)。我想知道的是如何将来自同一个目录中的文件的数据加载到 placesgj.geojson 中,其中将以geojson格式写入50,000个数据条目到变量 placez ,而不是像示例中那样在此处手动编写。其余的代码为了简洁而被忽略,与功能无关。预先感谢!

var placez = {
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "icon": "theatre"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-77.038659, 38.931567]
        }
    }, {
        "type": "Feature",
        "properties": {
            "icon": "music"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-77.007481, 38.876516]
        }
    }]
};
map.on('load', function() {
    // Add a GeoJSON source containing place coordinates and information.
    map.addSource("placer", {
        "type": "geojson",
        "data": placez
    });
    placez.features.forEach(function(feature) {
        var symbol = feature.properties['icon'];
        var layerID = 'poi-' + symbol;

2 个答案:

答案 0 :(得分:1)

这是将JSON文件加载到javascript对象中的情况。可以使用XMLHttpRequest在纯Java脚本中完成。

 function loadJSONFile(callback) {   

    var xmlobj = new XMLHttpRequest();

    xmlobj.overrideMimeType("application/json");

    xmlobj.open('GET', 'placesgj.geojson', true); // Provide complete path to your json file here. Change true to false for synchronous loading.

    xmlobj.onreadystatechange = function () {
          if (xmlobj.readyState == 4 && xmlobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xmlobj.responseText);
          }
    };

    xmlobj.send(null);  
 }

通过传递如下所示的回调函数来调用loadJSONFile函数:

loadJSONFile(function(response) {
    var placez = JSON.parse(response);
 });

//继续您的map.on('load',..代码在这里...

答案 1 :(得分:0)

使用Fetch API来读取文件。

function fetchJSON(url) {
  return fetch(url)
    .then(function(response) {
      return response.json();
    });
}

假设placesgj.geojson在同一目录中:

var data = fetchJSON('placesgj.geojson')
            .then(function(data) { 

        // do what you want to do with `data` here...
        data.features.forEach(function(feature) {
                console.log(feature);
                var symbol = feature.properties['icon'];
                console.log(symbol);
            });

});