Quick Start
This guide will help you create your first MapboxGL map in 5 minutes.
1. Include MapboxGL
Via CDN
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My First Map</title>
<!-- Mapbox GL JS -->
<script src="https://cdn.jsdelivr.net/npm/mapbox-gl@3.7.0/dist/mapbox-gl.min.js"></script>
<!-- Mapbox GL CSS -->
<link href="https://cdn.jsdelivr.net/npm/mapbox-gl@3.7.0/dist/mapbox-gl.min.css" rel="stylesheet">
<style>
body { margin: 0; padding: 0; }
#map { width: 100%; height: 100vh; }
</style>
</head>
<body>
<div id="map"></div>
<script>
// Initialize map
const map = new mapboxgl.Map({
container: 'map', // Container ID
style: 'mapbox://styles/mapbox/streets-v12', // Map style
center: [116.3974, 39.9093], // Initial center [longitude, latitude]
zoom: 11 // Initial zoom level
});
</script>
</body>
</html>Via npm
bash
npm install mapbox-gljavascript
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [116.3974, 39.9093],
zoom: 11
})2. Get Access Token
To use MapboxGL, you need a valid access token:
- Register for a Mapbox account
- Create an access token
- Set the token in your code:
javascript
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'WARNING
Don't commit your access token to public repositories. Use environment variables to store sensitive information.
3. Complete Example
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Map</title>
<script src="https://cdn.jsdelivr.net/npm/mapbox-gl@3.7.0/dist/mapbox-gl.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/mapbox-gl@3.7.0/dist/mapbox-gl.min.css" rel="stylesheet">
<style>
body { margin: 0; padding: 0; }
#map { width: 100%; height: 100vh; }
</style>
</head>
<body>
<div id="map"></div>
<script>
// Set access token
mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN'
// Initialize map
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v12',
center: [116.3974, 39.9093],
zoom: 11,
bearing: 0,
pitch: 0
})
// Add navigation control
map.addControl(new mapboxgl.NavigationControl())
// Add marker
new mapboxgl.Marker()
.setLngLat([116.3974, 39.9093])
.setPopup(new mapboxgl.Popup().setHTML('<h3>Beijing</h3><p>Welcome to Beijing!</p>'))
.addTo(map)
</script>
</body>
</html>4. Common Configuration Options
| Option | Type | Description |
|---|---|---|
container | string | Map container ID |
style | string | Map style URL |
center | Array | Initial center point [longitude, latitude] |
zoom | number | Initial zoom level (0-22) |
bearing | number | Map rotation angle (0-360) |
pitch | number | Map pitch angle (0-85) |