me
me copied to clipboard
学习 Mapbox (Part 1: Hello World)
ref: Getting Started | Mapbox GL JS | Mapbox
-
yarn create vite
, project: foo, framework选择Vanilla - code打开foo, 在terminal中运行yarn安装依赖,然后yarn dev运行,打开可以看到vite默认页面
-
yarn add mapbox-gl
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mapbox GL JS map</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<script type="module" src="/main.js"></script>
<div id="map"></div>
</body>
</html>
main.js
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
mapboxgl.accessToken = 'your-mapbox-token';
const map = new mapboxgl.Map({
container: 'map', // container ID
style: 'mapbox://styles/mapbox/streets-v12', // style URL
center: [121.5934326349772, 31.240585170245282], // CEIBS
zoom: 16 // starting zoom
});
通过调整style, pitch (倾斜角度), bearing (旋转角度)就可以得到一个你想要的视角
const map = new mapboxgl.Map({
container: 'map', // container ID
antialias: true,
// style: 'mapbox://styles/mapbox/streets-v12', // 标准背景
style: 'mapbox://styles/mapbox/light-v11', // 浅色背景
center: [121.5934326349772, 31.240585170245282],
pitch: 60, // 俯仰角
bearing: -65, // 旋转角
zoom: 17
});
注: Mac下按住control三指可以改变倾斜和旋转角度。
打开默认的3d layer可以看到如下画面:
map.on('load', function () {
// 添加3D建筑图层
map.addLayer({
'id': '3d-buildings',
'source': 'composite',
'source-layer': 'building',
'filter': ['==', 'extrude', 'true'],
'type': 'fill-extrusion',
'minzoom': 15,
'paint': {
'fill-extrusion-color': '#aaa', // 3D建筑物颜色
'fill-extrusion-height': ['get', 'height'], // 使用建筑物高度
'fill-extrusion-base': ['get', 'min_height'], // 使用建筑物基础高度
'fill-extrusion-opacity': 0.6, // 设置透明度
}
});
});
收工。
下一步需要增加3D模型,包括低精度和高精度两种类型:
- Maps | Mapbox
- Add a 3D model | Mapbox GL JS | Mapbox
- Add a 3D model with threebox | Mapbox GL JS | Mapbox
glTF/glB online viewer: glTF Viewer