如何通过来自额外json文件的数据来更改特性的样式/属性?(MapBox 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具有参数为"name"的项(功能(。

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

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

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

我是MapBox的新手,有这么多基于参数的函数,我会迷失方向。请帮助我通过查找各州的名称("New York"等(,用color from 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中的其他参数我在弹出窗口中显示,这与这种额外的文件方法配合得很好。(

您可以在添加源之前使用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/

最新更新