javascript - 使用 Mapbox 读取本地 geojson 文件

标签 javascript json mapbox geojson mapbox-gl-js

我目前正在尝试使用 Mapbox 进行简单的可视化,该可视化基于本地 geojson 文件提供的附加数据。我无法将此文件上传到 Mapbox,并希望将其保留在本地。

我用过this base code from Mapbox我已经修改为包含一个本地 geojson 文件,其结构如下:

{"features": [{"geometry": null, "location": {"coordinates": [40.730610, -73.935242], "type": "Point"}, "properties": {"X": "1", "group": "1"}, "type": "Feature"},...}

我已经修改了 Mapbox 中的示例代码,现在是:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>Style circles with a data-driven property</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.js'></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.48.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibG9ubmliZXNhbmNvbiIsImEiOiJjamxjaWNpOHQwMHV0M3FwaHhneGhvY2l2In0.7GxI8W_dnTKITNF4hEvZeQ';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    zoom: 12,
    center: [-73.935242, 40.730610],
    pitch: 20,
});


var url = "GeoObs.json.json"

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

    var layers = map.getStyle().layers;

    var labelLayerId;
    for (var i = 0; i < layers.length; i++) {
        if (layers[i].type === 'symbol' && layers[i].layout['text-field']) {
            labelLayerId = layers[i].id;
            break;
        }
    }

     map.addSource("my_data", {
        type: "geojson",
        data: url //"./GeoObs.json",
        /*cluster: true,
        clusterMaxZoom: 15, // Max zoom to cluster points on
        clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)*/
    });


    map.addLayer({
        'id': 'population',
        'type': 'circle',
        source: 'my_data',
        'source-layer': 'my_data',
        'paint': {
            // make circles larger as the user zooms from z12 to z22
            'circle-radius': {
                'base': 1.75,
                'stops': [[12, 2], [22, 180]]
            },
            // color circles by ethnicity, using a match expression
            // https://www.mapbox.com/mapbox-gl-js/style-spec/#expressions-match
            'circle-color': [
                'match',
                ['get', 'group'],
                '1', '#fbb03b',
                '2', '#223b53',
                '3', '#e55e5e',
                '4', '#3bb2d0',
                /* other */ '#ccc'
            ]
        }
    });

    map.addLayer({
        'id': '3d-buildings',
        'source': 'composite',
        'source-layer': 'building',
        'filter': ['==', 'extrude', 'true'],
        'type': 'fill-extrusion',
        'minzoom': 15,
        'paint': {
            'fill-extrusion-color': '#aaa',

            // use an 'interpolate' expression to add a smooth transition effect to the
            // buildings as the user zooms in
            'fill-extrusion-height': [
                "interpolate", ["linear"], ["zoom"],
                15, 0,
                15.05, ["get", "height"]
            ],
            'fill-extrusion-base': [
                "interpolate", ["linear"], ["zoom"],
                10, 0,
                15.05, ["get", "min_height"]
            ],
            'fill-extrusion-opacity': .6
        }
    }, labelLayerId);
});

</script>

</body>
</html>

我收到以下错误:

Error: Source layer "my_data" does not exist on source "my_data" as specified by style layer "population"
    at i._validateLayer (style.js:274)
    at i.addLayer (style.js:576)
    at o.addLayer (map.js:1175)
    at o.<anonymous> (index3.html:52)
    at o.L.fire (evented.js:115)
    at o._render (map.js:1619)
    at map.js:1683

任何人都可以指出我这里可能出现的错误,并希望如何解决它。您可以使用我给您的示例 geojson 来尝试这个示例。如果您希望代码立即给出相同的错误,只需将其复制粘贴到名为:GeoObs.json 的文件中即可。

最佳答案

正如错误所述,您的 GeoJSON 源没有源层。因此,您可以从 map.addLayer 调用中删除 'source-layer' 属性。

您的 GeoJSON 还需要修改为适当的特征集合:

{
  "type": "FeatureCollection",
  "features": [
    {
      "geometry": {
        "type": "Point",
        "coordinates": [
          -73.935242,
          40.730610
        ]
      },
      "properties": {
        "X": "1",
        "group": "1"
      },
      "type": "Feature"
    }
  ]
}

关于javascript - 使用 Mapbox 读取本地 geojson 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52298968/

相关文章:

javascript - 如何从我的phonegap应用程序调用服务器API?

javascript - YouTube json feed 返回所有结果

javascript - 首次单击 Mapbox map 后,GeoJson LineString 仅加载一次

mapbox - react-map-gl 没有 API key 使用 osm 瓷砖

flutter |如何在 Mapbox 的标记/符号中添加自定义图标

javascript - 减去不透明度而不是乘以

javascript - 如果需要空字段属性

javascript - 检查 Mongoose 模型变量中是否存在不需要的属性

javascript - angularJS ng重复字段和特殊字符

java - Android - gson.toJson 在 ArrayList<OverlayItem> 上抛出 StackOverFlowError