Getting started overview
This guide outlines the essential steps for developers to initiate their work with Mapbox. It covers the process of setting up a Mapbox account, generating the necessary access tokens for API authentication, and making a foundational API request. The objective is to enable a quick first integration, allowing users to display a basic interactive map within a web application. Mapbox provides a suite of APIs for mapping, navigation, and location-based services, alongside tools like Mapbox Studio for map customization Mapbox documentation portal.
The following table provides a quick reference for the initial setup:
| Step | What to do | Where |
|---|---|---|
| 1. Account Creation | Register for a free Mapbox account. | Mapbox signup page |
| 2. Access Token Generation | Locate or create a public access token. | Mapbox account dashboard |
| 3. Environment Setup | Set up a basic HTML file with Mapbox GL JS. | Local development environment |
| 4. First Request | Embed a map using the access token and Mapbox GL JS. | HTML file script section |
Create an account and get keys
To begin using Mapbox, a user account is required. This account provides access to the Mapbox dashboard, where API access tokens are managed and usage statistics are monitored. Mapbox offers a free tier that includes a specified number of monthly map loads and API requests, suitable for initial development and testing Mapbox pricing details.
Account Registration
- Navigate to the Mapbox signup page.
- Provide a valid email address, desired username, and a strong password.
- Complete the registration process, which typically involves email verification.
- Once registered, log in to the Mapbox account dashboard.
Access Token Generation and Management
Mapbox APIs are authenticated using access tokens. These tokens are unique identifiers that link API requests to your Mapbox account and control access to specific Mapbox services. Public tokens are generally safe for client-side use, while secret tokens should be protected on a server-side environment Mapbox access token glossary.
- After logging into your Mapbox account, navigate to the Access tokens section.
- A default public access token is usually generated automatically upon account creation. This token can be used for most client-side applications, such as embedding maps directly into a web page.
- If a new token is needed, click the Create a token button.
- Assign a descriptive name to the new token (e.g., "My Web App Map").
- Ensure the token has the necessary scopes (permissions) for your intended use case. For displaying a basic map, the
styles:readandmaps:readscopes are typically sufficient. - Copy the generated public access token. This token will be used in your application code to authenticate requests to Mapbox APIs.
It is crucial to manage access tokens securely. Public tokens, while designed for client-side use, should still be handled with care to prevent unauthorized use. For server-side operations or sensitive data, Mapbox recommends using secret access tokens and ensuring they are stored securely and never exposed in client-side code Mapbox access token security guide.
Your first request
This section demonstrates how to embed a basic interactive map into a web page using Mapbox GL JS, the primary JavaScript library for displaying Mapbox maps on the web. This process involves including the Mapbox GL JS library and stylesheet, then initializing a map object with your access token.
Prerequisites
- A text editor (e.g., VS Code, Sublime Text).
- A web browser for testing (e.g., Chrome, Firefox).
- Your Mapbox public access token.
Steps to Display a Map
-
Create an HTML file: Create a new file named
index.htmlin your project directory.<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My First Mapbox Map</title> <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"> <link href="https://api.mapbox.com/mapbox-gl-js/v3.4.0/mapbox-gl.css" rel="stylesheet"> <script src="https://api.mapbox.com/mapbox-gl-js/v3.4.0/mapbox-gl.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 = 'YOUR_MAPBOX_ACCESS_TOKEN'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v12', // style URL center: [-74.5, 40], // starting position [lng, lat] zoom: 9 // starting zoom }); </script> </body> </html> -
Replace the placeholder: In the JavaScript section, replace
'YOUR_MAPBOX_ACCESS_TOKEN'with your actual public access token copied from the Mapbox dashboard. -
Open the file: Save
index.htmland open it in your web browser. You should see an interactive map centered near the specified coordinates.
This example uses the mapbox/streets-v12 style, which is one of Mapbox's default map styles. Mapbox GL JS automatically handles rendering the map and interacting with Mapbox's vector tile services Mapbox GL JS API reference.
Common next steps
After successfully displaying a basic map, developers often explore further customization and advanced features. Mapbox provides extensive capabilities for tailoring maps to specific application requirements.
-
Customizing Map Styles with Mapbox Studio: Mapbox Studio is a web-based editor that allows users to create and customize map styles without writing code. You can upload custom data, design visual elements, and publish unique map styles. These styles can then be referenced in your application using their unique style URL Mapbox Studio overview.
-
Adding Data to the Map: Beyond base maps, you can add various data layers, such as markers, lines, and polygons, to your map. Mapbox GL JS supports adding data from GeoJSON, vector tiles, and raster sources. This enables the visualization of custom information relevant to your application Mapbox GL JS add GeoJSON example.
-
Implementing User Interaction: Mapbox GL JS provides APIs for handling user interactions like clicks, hovers, and drags. This allows for dynamic map applications where users can interact with map features to trigger events or display information. For example, you can add popups on marker clicks or change feature styles on hover Mapbox GL JS popup on click example.
-
Exploring Other Mapbox APIs: Mapbox offers a range of other APIs beyond the core Maps API:
- Geocoding API: Convert addresses to coordinates (geocoding) and coordinates to addresses (reverse geocoding) Mapbox Geocoding API documentation.
- Navigation API: Calculate routes, provide turn-by-turn directions, and estimate travel times Mapbox Navigation API documentation.
- Search Box API: Implement powerful search experiences with autocomplete and location biasing Mapbox Search Box API documentation.
- Static Images API: Generate static map images for use in emails, print, or as fallback images Mapbox Static Images API documentation.
-
Evaluating Performance: As applications scale, monitoring API usage and optimizing map performance becomes important. Mapbox provides tools in the dashboard to track usage against your free tier limits and understand billing. Techniques like data simplification, efficient styling, and proper caching can improve map load times and responsiveness Mapbox map performance optimization.
-
Learning about API Security: Understanding how to secure your API keys and manage access is crucial for production applications. While public tokens are used client-side, secret tokens for server-side operations require careful handling, often involving environment variables or secure key management systems. For general API security principles, the OAuth 2.0 framework is a widely adopted standard for delegated authorization in APIs.
Troubleshooting the first call
Encountering issues during the initial setup is common. Here are some frequent problems and their solutions when making your first Mapbox API call:
-
"Access Token Not Valid" or "Unauthorized" Error:
- Check for typos: Ensure your
mapboxgl.accessTokenstring is an exact match to the token from your Mapbox dashboard. Copy-pasting is recommended. - Token type: Verify you are using a public access token for client-side Mapbox GL JS applications. Secret tokens will not work in this context.
- Token scopes: Confirm that the token has the necessary scopes (permissions) activated. For basic map display,
styles:readandmaps:readare essential. You can review and adjust token scopes in your Mapbox account access tokens page. - Token expiration: While public tokens generally don't expire, custom tokens might have expiration dates set. Check the token's details in your dashboard.
- Check for typos: Ensure your
-
Map Container Not Visible or Blank:
- CSS issues: Ensure the
#mapdiv has defined dimensions (width and height) and is visible. The provided CSS snippetposition: absolute; top: 0; bottom: 0; width: 100%;is a common way to make the map fill the viewport. If your map is inside another container, ensure that container also has defined dimensions. - HTML structure: Verify that the
containerproperty innew mapboxgl.Map()correctly references the ID of your map container element (e.g.,'map'for<div id="map"></div>). - Script loading order: Make sure the Mapbox GL JS script and stylesheet are loaded correctly in the
<head>section, and your map initialization script runs after the<div id="map"></div>element is present in the DOM.
- CSS issues: Ensure the
-
Console Errors (Browser Developer Tools):
- JavaScript errors: Open your browser's developer console (F12 or right-click > Inspect > Console tab) to check for JavaScript errors. These often provide specific clues about what went wrong.
- Network requests: In the developer tools' Network tab, check if requests to
api.mapbox.comare being made and if they are returning successful 200 responses. Look for any failed requests (e.g., 401 Unauthorized, 403 Forbidden, 404 Not Found).
-
Map Not Loading Correct Style:
- Style URL: Double-check the
styleURL in yourmapboxgl.Mapconstructor (e.g.,'mapbox://styles/mapbox/streets-v12'). If you're using a custom style from Mapbox Studio, ensure the URL is correct and the style is published.
- Style URL: Double-check the
-
Cross-Origin Resource Sharing (CORS) Issues:
- While less common with direct Mapbox GL JS usage, if you are loading resources from different domains, ensure your server or the external resource's server is configured to allow CORS requests from your domain. Mapbox's own APIs generally handle CORS correctly for client-side requests.
-
Refer to Mapbox Documentation and Community:
- The Mapbox Help & Support page is an excellent resource for detailed troubleshooting guides and FAQs.
- The Mapbox community forums and Stack Overflow often contain solutions to common problems encountered by other developers.