首页 > 解决方案 > 如何通过额外 json 文件中的数据更改特征的样式/属性?(地图盒 GL)

问题描述

到目前为止,我有一张地图(MapBox GL),它绘制了有边界的县。

    map.addSource('states', {
        'type': 'geojson',
        'data': '/geojson/county_boundaries.geojson'
    });

    map.addLayer({ // adding borders:
        'id': 'state-borders',
        'type': 'line',
        'source': 'states',
        'layout': {},
        'paint': {
            'line-color': '#627BC1',
            'line-width': 2
        }
    });

该county_borders.geojson 包含带有参数“名称”的项目(特征)。

...
   "features": [
       { "type": "Feature", "id": 8, "properties": { "name": "New York", ...

我有另一个 stats.json 文件,其中包含大多数功能的属性,其中“名称”是主键。

    "New York": {
        "Population": "500123",
        "Food Consumption Level": "3",
        "Color": "#e67800"
    },

我是 MapBox 的新手,有这么多基于参数的函数,我迷路了。请帮助我通过查找它们的名称(“纽约”等)使用 stats.json 文件中的颜色更改所有州的填充颜色。我想我需要遍历所有功能并以某种方式设置它们的填充。

我发现用相同的默认颜色填充状态的唯一方法是这样的:

    map.addLayer({
        'id': 'state-fills',
        'type': 'fill',
        'source': 'states',
        'layout': {},
        'paint': {
            'fill-color': '#627BC1',
            'fill-opacity': [
                'case',
                ['boolean', ['feature-state', 'hover'], false],
                1,
                0.5
            ]
        }
    });

它正在努力填补所有州。但不是我需要的。我想动态修改每个状态运行时的颜色,而不更改原始 geojson 文件。(我在弹出窗口中显示的 data.json 中的其他参数,它适用于这种额外的文件方法。)

标签: mapboxmapbox-gl-js

解决方案


您可以在添加源之前使用 Javascript 将统计信息添加到 GeoJSON 中,而不是将原始 GeoJSON 文件作为源添加到地图中:

var geojson = addStats(originalGeojson, stats);
map.addSource('states', {
    'type': 'geojson',
    'data': geojson
});

function addStats(geojson, stats) {
  geojson.features.forEach((feature) => {
    var statsForFeature = stats[feature.properties.name];
    if (statsForFeature) {
      // add stats to the feature's properties
      feature.properties = Object.assign(feature.properties, statsForFeature);
    }
  });

  return geojson;
}

之后,您可以使用图层类型“填充”的数据驱动样式来为您的功能着色:

map.addLayer({ // adding borders:
  'id': 'state-borders',
  // use type 'fill'
  'type': 'fill',
  'source': 'states',
  'layout': {},
  'paint': {
    'fill-outline-color': '#627BC1',
    // use data-driven styling
    'fill-color': ['get', 'Color'],
  },
});

这是一个演示此技术的工作示例:https ://jsfiddle.net/0s17mqvh/


推荐阅读