Getting started overview
Integrating Mapbox GL JS into a web application involves a series of steps that begin with account creation and end with a functional, interactive map display. This guide outlines the process from initial setup to rendering your first map, focusing on the essential requirements to get Mapbox GL JS operational. The core components include obtaining a Mapbox access token, incorporating the Mapbox GL JS library into your project, and writing JavaScript to initialize and configure the map.
Mapbox GL JS is a client-side JavaScript library that renders vector tiles and Mapbox styles as interactive maps in a web browser using WebGL. It is designed for performance and customization, allowing developers to control map appearance and behavior directly within the browser (Mapbox GL JS API reference).
Quick Reference Guide
| Step | What to Do | Where |
|---|---|---|
| 1. Create Account | Register for a free Mapbox account. | Mapbox signup page |
| 2. Get Access Token | Locate or generate a public access token. | Mapbox account access tokens |
| 3. Project Setup | Create an HTML file and link Mapbox GL JS CSS and JS. | Local development environment |
| 4. Initialize Map | Add JavaScript to create a map instance with your token and style. | HTML file script block |
| 5. Verify | Open the HTML file in a browser to confirm map display. | Web browser |
Create an account and get keys
Before using Mapbox GL JS, you need a Mapbox account to obtain an access token. This token authenticates your requests to Mapbox services, including map tiles and styles (Mapbox GL JS authentication documentation).
1. Sign up for a Mapbox account
Navigate to the Mapbox signup page and complete the registration process. Mapbox offers a free tier that provides a set number of map loads and active users per month, suitable for development and small-scale applications (Mapbox pricing details).
2. Locate your public access token
Once logged into your Mapbox account, your default public access token is usually available on your Mapbox account dashboard under the Access tokens section. This token is required for all requests made to Mapbox services through Mapbox GL JS. It is a public token, meaning it can be exposed in client-side code without compromising your account security, unlike a secret token (Mapbox access token types overview).
If you need to generate a new token or manage existing ones, you can do so from the same access tokens page. For development purposes, the default public token is sufficient. For production environments, it is recommended to create specific tokens with restricted scopes to limit potential misuse (Mapbox token security best practices).
Your first request
This section guides you through creating a simple web page that displays a basic Mapbox GL JS map. This involves setting up your HTML structure, including the necessary Mapbox GL JS library files, and writing the JavaScript to initialize the map.
1. Create an HTML file
Create a new HTML file (e.g., index.html) and add the basic HTML5 structure. Inside the <head> section, link to the Mapbox GL JS CSS file. This stylesheet provides the default styling for the map controls and elements. In the <body>, include a <div> element that will serve as the container for your map.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mapbox GL JS First Map</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://api.mapbox.com/mapbox-gl-js/v3.3.0/mapbox-gl.css" rel="stylesheet"> <!-- Replace with latest version -->
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://api.mapbox.com/mapbox-gl-js/v3.3.0/mapbox-gl.js"></script> <!-- Replace with latest version -->
<script>
// Your JavaScript will go here
</script>
</body>
</html>
Note: Always refer to the official Mapbox GL JS API documentation for the latest stable versions of the CDN links for the CSS and JavaScript files.
2. Initialize the map with JavaScript
Within the <script> tags in your HTML file, add the JavaScript code to initialize your map. You will need to replace 'YOUR_MAPBOX_ACCESS_TOKEN' with your actual public access token obtained from your Mapbox account.
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';
const map = new mapboxgl.Map({
container: 'map', // The ID of the HTML element where the map will be rendered
style: 'mapbox://styles/mapbox/streets-v12', // A Mapbox style URL. streets-v12 is a common base map.
center: [-74.0060, 40.7128], // Starting position [longitude, latitude] (e.g., New York City)
zoom: 9 // Starting zoom level
});
// Optional: Add navigation controls (zoom in/out, compass)
map.addControl(new mapboxgl.NavigationControl());
Explanation of parameters:
mapboxgl.accessToken: Your public Mapbox access token. This is crucial for authenticating your requests to Mapbox services.container: The ID of the HTML element where the map will be embedded. In this example, it's'map'.style: The URL of the Mapbox style to use. Mapbox provides several default styles, such asmapbox://styles/mapbox/streets-v12,light-v11, ordark-v11. You can also create custom styles using Mapbox Studio.center: An array specifying the initial longitude and latitude of the map's center.zoom: The initial zoom level of the map. Higher numbers mean more zoomed in.
3. View your map
Save the index.html file and open it in a web browser. You should see an interactive map centered on the specified coordinates with the chosen style. If the map does not load, review the troubleshooting section below.
Common next steps
Once you have a basic map displaying, you can explore various features and functionalities offered by Mapbox GL JS:
- Adding Markers and Popups: Display points of interest on your map using
mapboxgl.Markerandmapboxgl.Popup. - Drawing Geometries: Add lines (polylines) and polygons to represent routes, boundaries, or areas on your map. This typically involves using GeoJSON sources and layers.
- Custom Styling: Beyond using default Mapbox styles, you can create your own custom map styles using Mapbox Studio or by programmatically modifying map layers and sources with the Mapbox Style Specification.
- Loading External Data: Integrate external GeoJSON data, vector tiles, or raster tiles from various sources into your map. For example, you might fetch data from a Google Maps Platform Elevation API or a custom backend to display dynamic information.
- User Interaction: Implement event listeners to respond to user interactions like clicks, hovers, and drags on map features. The
map.on()method is key for this. - Performance Optimization: For complex maps with many features, consider techniques like clustering, data driven styling, or rendering large datasets as vector tiles using Mapbox Tiling Service for optimal performance.
Troubleshooting the first call
If your Mapbox GL JS map isn't displaying correctly or you encounter errors, consider the following common issues:
- Access Token Errors:
- "Unauthorized" or "Forbidden" messages: Double-check that your
mapboxgl.accessTokenis correctly set in your JavaScript code and that it matches a valid public access token from your Mapbox account. Ensure there are no typos or extraneous characters. - Token scope: Verify that the access token has the necessary scopes (permissions) to access the requested Mapbox services (e.g.,
styles:readfor map styles). Default public tokens usually have broad read access.
- "Unauthorized" or "Forbidden" messages: Double-check that your
- CDN Link Issues:
- Incorrect versions: Ensure the CSS and JavaScript CDN links (
mapbox-gl.cssandmapbox-gl.js) are for the same, correct version of Mapbox GL JS. Mismatched versions can lead to rendering problems or script errors. Always refer to the Mapbox GL JS documentation for the latest stable CDN links. - Network access: Confirm that your browser has internet access and is not blocked by a firewall from reaching
api.mapbox.com.
- Incorrect versions: Ensure the CSS and JavaScript CDN links (
- HTML Structure and Styling:
- Missing map container: The
containerproperty innew mapboxgl.Map()must exactly match theidof an existing HTML<div>element (e.g.,id="map"). - Map container dimensions: The map container
<div>must have defined width and height, either through CSS (as shown in the example#map { position: absolute; top: 0; bottom: 0; width: 100%; }) or inline styles. A container with zero dimensions will not display a map.
- Missing map container: The
- JavaScript Errors:
- Browser developer console: Open your browser's developer console (usually F12 or right-click > Inspect > Console tab) to check for JavaScript errors. These errors often provide specific details about what went wrong.
- Script loading order: Ensure that the
mapbox-gl.jsscript is loaded before your custom JavaScript code that initializes the map.
- Map Style Issues:
- Invalid style URL: Verify that the
styleURL (e.g.,'mapbox://styles/mapbox/streets-v12') is correct and accessible. If you're using a custom style, ensure it's published and permissions are set correctly.
- Invalid style URL: Verify that the