我正在使用mapbox示例以便在地图上创建多个多边形,并且每个都有弹出事件。我的问题是我需要根据它的geojson属性设置每个多边形的填充颜色。
This就是我的榜样。 我使用以下javascript代码:
mapboxgl.accessToken = 'pk.eyJ1IjoibWFoYW5tZWhydmFyeiIsImEiOiJ6SDdSWldRIn0.8zUNm01094D1aoSeHpWYqA';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [51.40545845031738,
35.75069181054449],
zoom: 10
});
map.on('load', function (e) {
// Add a layer showing the state polygons.
map.addLayer({
'id': 'states-layer',
'type': 'fill',
'source': {
'type': 'geojson',
'data': 'geojson.js'
},
'paint': {
'fill-color': 'rgba(200, 100, 240, 0.4)',
'fill-outline-color': 'rgba(200, 100, 240, 1)'
}
});
// When a click event occurs on a feature in the states layer, open a popup at the
// location of the click, with description HTML from its properties.
map.on('click', 'states-layer', function (e) {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
//.setHTML(e.features[0].properties.name)
.setHTML("<h1>"+e.features[0].properties.userone+"</h1>"+e.features[0].properties.name)
.addTo(map);
});
// Change the cursor to a pointer when the mouse is over the states layer.
map.on('mouseenter', 'states-layer', function () {
map.getCanvas().style.cursor = 'pointer';
});
// Change it back to a pointer when it leaves.
map.on('mouseleave', 'states-layer', function () {
map.getCanvas().style.cursor = '';
});
});
这里它加载所有相同的颜色
'paint': {
'fill-color': 'rgba(200, 100, 240, 0.4)',
'fill-outline-color': 'rgba(200, 100, 240, 1)'
}
在我的geojson文件中,我有一个颜色键:
"type": "Feature",
"properties": {
"userone":"پیروزی",
"name":"North Dafkota",
"featureclass":"Admin-1 scale rank",
"color":"red"
}
我想用它来定义多边形填充颜色。
答案 0 :(得分:5)
如果您只想使用在geojson要素属性中定义的颜色。然后你可以像这样使用层标识属性:
map.addLayer({
'id': 'states-layer',
'type': 'fill',
'source': {
'type': 'geojson',
'data': 'geojson.js'
},
'paint': {
'fill-color': {
type: 'identity',
property: 'color',
},
'fill-outline-color': 'rgba(200, 100, 240, 1)'
}
});
&#13;
另见:https://www.mapbox.com/mapbox-gl-js/style-spec/#function-type
并且:https://www.mapbox.com/mapbox-gl-js/style-spec/#types-color