<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Add a polygon to a map using a GeoJSON source</title>
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<link
href="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.css"
rel="stylesheet"
/>
<script src="https://api.mapbox.com/mapbox-gl-js/v2.14.1/mapbox-gl.js"></script>
<script src="./data/js/china.js"></script>
<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.eyJ1IjoibHh0aWFudGlhbiIsImEiOiJjaXd2ZjlkYnQwMTZvMnRtYWZnM2lpbHFvIn0.ef3rFZTr9psmLWahrqap2A";
const map = new mapboxgl.Map({
container: "map", // container ID
style: "mapbox://styles/mapbox/streets-v12", // style URL
center: [105.39, 39.6], // starting position
zoom: 3, // starting zoom
});
resolveChinaJson();
map.on("load", () => {
map.addSource("maine", {
type: "geojson",
data: chinaJson,
});
map.addLayer({
id: "maine",
type: "fill-extrusion",
source: "maine", // reference the data source
layout: {},
paint: {
"fill-extrusion-vertical-gradient": true,
"fill-extrusion-color": ["get", "color"],
// "fill-extrusion-color": '#79D0F0',
"fill-extrusion-height": ["get", "count"],
"fill-extrusion-base": 0,
"fill-extrusion-opacity": 1.0,
},
});
// Add a black outline around the polygon.
// map.addLayer({
// 'id': 'outline',
// 'type': 'line',
// 'source': 'maine',
// 'layout': {},
// 'paint': {
// 'line-color': '#000',
// 'line-width': 3
// }
// });
});
// 获取json数据
function resolveChinaJson () {
const countMap = {
'650000': 300, // 新疆车辆数
'150000': 100, // 内蒙
'370000': 50, // 山东
};
chinaJson.features.forEach(feature => {
feature.properties.color = getRandomColor();
if(countMap[feature.properties.adcode]){
feature.properties.count = 10000 + countMap[feature.properties.adcode] * 1000;
}else{
feature.properties.count = 10000;
}
});
}
// 生成随机颜色
function getRandomColor() {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
</script>
</body>
</html>
效果: