添加GeoJSON多边形
使用GeoJSON源和填充图层添加多边形到地图;
<!DOCTYPE html>
<html lang="en">
<head>
<title>添加GeoJSON多边形</title>
<meta property="og:description" content="使用GeoJSON源和填充图层添加多边形到地图" />
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel='stylesheet' href='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.css' />
<script src='https://unpkg.com/maplibre-gl@5.5.0/dist/maplibre-gl.js'></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new maplibregl.Map({
container: 'map',
style: 'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL',
center: [-68.13734351262877, 45.137451890638886],
zoom: 5
});
map.on('load', () => {
// 添加一个数据源,其中包含GeoJSON格式的数据
map.addSource('maine', {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'Polygon',
// 这些坐标绘制了缅因州的边界
'coordinates': [
[
[-67.13734, 45.13745],
[-66.96466, 44.8097],
[-68.03252, 44.3252],
[-69.06, 43.98],
[-70.11617, 43.68405],
[-70.64573, 43.09008],
[-70.75102, 43.08003],
[-70.79761, 43.21973],
[-70.98176, 43.36789],
[-70.94416, 43.46633],
[-71.08482, 45.30524],
[-70.66002, 45.46022],
[-70.30495, 45.91479],
[-70.00014, 46.69317],
[-69.23708, 47.44777],
[-68.90478, 47.18479],
[-68.2343, 47.35462],
[-67.79035, 47.06624],
[-67.79141, 45.70258],
[-67.13734, 45.13745]
]
]
}
}
});
// 添加一个填充图层
map.addLayer({
'id': 'maine',
'type': 'fill',
'source': 'maine', // 引用上面创建的数据源
'layout': {},
'paint': {
'fill-color': '#0080ff', // 蓝色填充
'fill-opacity': 0.5
}
});
// 添加一个描边图层
map.addLayer({
'id': 'outline',
'type': 'line',
'source': 'maine',
'layout': {},
'paint': {
'line-color': '#000',
'line-width': 3
}
});
});
</script>
</body>
</html>