← Plugin catalog
Developer Tools

Mapbox

Mapbox, Inc. v1.0.2

Location Intelligence

Create a free account to save this plugin.

From the developer

Not specified in the available declarations: capabilities, limitations, pricing & account requirements.

Onboarding example

I need to add a Mapbox map to my SwiftUI app, what's the right way to set it up?
Sources & dates

Developer declarations; not independently tested. Listing last checked Nov 19, 2026. Package observed Nov 19, 2026.

View package source →

Description

From the marketplace listing

Skills and an MCP server for building with Mapbox. The skills cover integration patterns for web, iOS, Android, and Flutter, along with map styling, cartography, search, and geospatial operations. The MCP server connects your AI agent to live Mapbox data: geocoding, routing, and isochrones, so it can build real maps and location features using current, accurate data.

Language: English · Automatically detected from descriptions.

Matches for “android app features”

Exact text from the indicated source. A mention alone does not establish support for your task.

Publisher description

Skills and an MCP server for building with Mapbox. The skills cover integration patterns for web, iOS, Android, and Flutter, along with map styling, cartography, search, and geospatial operations. The MCP server connects your AI agent to live Mapbox data: geocoding, routing, and isochrones, so it can build real maps and location features using current, accurate data.

Package name

app-6a2c0bf33cb48191884d842b15ad3c20

Publisher keywords · listing

maps mapping geocoding directions routing navigation places location geospatial gis

What changed

Similar plugins

Finding similar plugins… Results will appear here automatically.

Browse plugins →

Keywords

Files & skills

File archives

Plugin package162 files · 267 KBBrowse files →
Skill instructions
mapbox-android-patterns9.91 KB

View saved version →

---
name: mapbox-android-patterns
description: Official integration patterns for Mapbox Maps SDK on Android. Covers installation, adding markers, user location, custom data, styles, camera control, and featureset interactions. Based on official Mapbox documentation.
---

# Mapbox Android Integration Patterns

Official patterns for integrating Mapbox Maps SDK v11 on Android with Kotlin, Jetpack Compose, and View system.

**Use this skill when:**

- Installing and configuring Mapbox Maps SDK for Android
- Adding markers and annotations to maps
- Showing user location and tracking with camera
- Adding custom data (GeoJSON) to maps
- Working with map styles, camera, or user interaction
- Handling feature interactions and taps

**Official Resources:**

- [Android Maps Guides](https://docs.mapbox.com/android/maps/guides/)
- [API Reference](https://docs.mapbox.com/android/maps/api-reference/)
- [Example Apps](https://github.com/mapbox/mapbox-maps-android/tree/main/Examples)

---

## Installation & Setup

### Requirements

- Android SDK 21+
- Kotlin or Java
- Android Studio
- Free Mapbox account

### Step 1: Configure Access Token

Create `app/res/values/mapbox_access_token.xml`:

```xml
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">
    <string name="mapbox_access_token" translatable="false"
        tools:ignore="UnusedResources">YOUR_MAPBOX_ACCESS_TOKEN</string>
</resources>
```

**Get your token:** Sign in at [mapbox.com](https://account.mapbox.com/access-tokens/)

### Step 1b: Internet permission (required)

Maps need network access. Include this in `AndroidManifest.xml` — agents often omit it and only list location permissions later:

```xml
<uses-permission android:name="android.permission.INTERNET" />
```

### Step 2: Add Maven Repository

In `settings.gradle.kts`:

```kotlin
dependencyResolutionManagement {
    repositories {
        google()
        mavenCentral()
        maven {
            url = uri("https://api.mapbox.com/downloads/v2/releases/maven")
        }
    }
}
```

### Step 3: Add Dependency

In module `build.gradle.kts`:

```kotlin
android {
    defaultConfig {
        minSdk = 21
    }
}

dependencies {
    implementation("com.mapbox.maps:android:11.18.1")
}
```

**For Jetpack Compose:**

```kotlin
dependencies {
    implementation("com.mapbox.maps:android:11.18.1")
    implementation("com.mapbox.extension:maps-compose:11.18.1")
}
```

---

## Map Initialization

### Jetpack Compose Pattern

**Basic map:**

```kotlin
import androidx.compose.runtime.*
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.ui.Modifier
import com.mapbox.maps.extension.compose.*
import com.mapbox.maps.Style
import com.mapbox.geojson.Point

@Composable
fun MapScreen() {
    MapboxMap(
        modifier = Modifier.fillMaxSize()
    ) {
        // Initialize camera via MapEffect (Style.STANDARD loads by default)
        MapEffect(Unit) { mapView ->
            // Set initial camera position
            mapView.mapboxMap.setCamera(
                CameraOptions.Builder()
                    .center(Point.fromLngLat(-122.4194, 37.7749))
                    .zoom(12.0)
                    .build()
            )
        }
    }
}
```

**With ornaments:**

```kotlin
MapboxMap(
    modifier = Modifier.fillMaxSize(),
    scaleBar = {
        ScaleBar(
            enabled = true,
            position = Alignment.BottomStart
        )
    },
    compass = {
        Compass(enabled = true)
    }
) {
    // Style.STANDARD loads by default
}
```

### View System Pattern

**Layout XML (activity_map.xml):**

```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.mapbox.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_hei

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 8 — file references are metadata, not package contents.

mapbox-cartography7.13 KB

View saved version →

---
name: mapbox-cartography
description: Expert guidance on map design principles, color theory, visual hierarchy, typography, and cartographic best practices for creating effective and beautiful maps with Mapbox. Use when designing map styles, choosing colors, or making cartographic decisions.
---

# Mapbox Cartography Skill

This skill provides expert cartographic knowledge to help you design effective, beautiful, and functional maps using Mapbox.

## Core Cartographic Principles

### Visual Hierarchy

Maps must guide the viewer's attention to what matters most:

- **Most important**: POIs, user location, route highlights
- **Secondary**: Major roads, city labels, landmarks
- **Tertiary**: Minor streets, administrative boundaries
- **Background**: Water, land use, terrain

**Implementation:**

- Use size, color intensity, and contrast to establish hierarchy
- Primary features: high contrast, larger symbols, bold colors
- Background features: low contrast, muted colors, smaller text

### Color Theory for Maps

**Color Harmony:**

- **Analogous colors**: Use colors next to each other on color wheel (blue-green-teal) for cohesive designs
- **Complementary colors**: Use opposite colors (blue/orange, red/green) for high contrast emphasis
- **Monochromatic**: Single hue with varying saturation/brightness for elegant, minimal designs

**Color Psychology:**

- **Blue**: Water, trust, calm, professional (default for water bodies)
- **Green**: Parks, nature, growth, eco-friendly (vegetation, parks)
- **Red/Orange**: Urgent, important, dining (alerts, restaurants)
- **Yellow**: Caution, highlight, attention (warnings, selected items)
- **Gray**: Neutral, background, roads (infrastructure)

**Accessibility:**

- Ensure 4.5:1 contrast ratio for text (WCAG AA)
- Don't rely solely on color to convey information
- Test designs with colorblind simulators
- Avoid red/green combinations for critical distinctions

**Color Palette Templates:**

Light Theme (Day/Professional):

```json
{
  "background": "#f5f5f5",
  "water": "#a0c8f0",
  "parks": "#d4e7c5",
  "roads": "#ffffff",
  "buildings": "#e0e0e0",
  "text": "#333333"
}
```

Dark Theme (Night Mode):

```json
{
  "background": "#1a1a1a",
  "water": "#0d47a1",
  "parks": "#2e7d32",
  "roads": "#3a3a3a",
  "buildings": "#2d2d2d",
  "text": "#ffffff"
}
```

> **Road color rule for dark themes:** Roads must use neutral dark gray (`#3a3a3a`), visibly distinct from the background but not colored. Never style roads with amber, blue, or other hues — reserve color for app data layers (routes, markers). Colored base roads and colored data layers will compete visually. Local roads that blend into the background (`#1e1e1e` on `#1a1a1a`) create a "floating labels" problem where street names appear with no visible road beneath them.

High Contrast (Accessibility):

```json
{
  "background": "#000000",
  "water": "#0066ff",
  "parks": "#00ff00",
  "roads": "#ffffff",
  "buildings": "#808080",
  "text": "#ffffff"
}
```

Vintage/Retro:

```json
{
  "background": "#f4e8d0",
  "water": "#b8d4d4",
  "parks": "#c8d4a4",
  "roads": "#d4c4a8",
  "buildings": "#e4d4c4",
  "text": "#4a3828"
}
```

### Typography at Map Scale

**Font Selection:**

- **Sans-serif** (Roboto, Open Sans): Modern, clean, high legibility at small sizes - use for labels
- **Serif** (Noto Serif): Traditional, formal - use sparingly for titles or historic maps
- **Monospace**: Technical data, coordinates

**Text Sizing:**

```
Place labels (cities, POIs): 11-14px
Street labels: 9-11px
Feature labels (parks): 10-12px
Map title: 16-20px
Attribution: 8-9px
```

**Label Placement:**

- Point labels: Center or slightly offset (avoid overlap with symbol)
- Line labels: Follow line curve, repeat for long features
- Area labels: Center in polygon, sized appropriately
- Prioritize: Major features get labels first, minor features labeled if space allows

### Zoom Level Strategy

**Zoom 0-4** (World to Continent):

- Major country boundaries
- Ocean an

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 4 — file references are metadata, not package contents.

mapbox-data-visualization-patterns8.36 KB

View saved version →

---
name: mapbox-data-visualization-patterns
description: Patterns for visualizing data on maps including choropleth maps, heat maps, 3D visualizations, data-driven styling, and animated data. Covers layer types, color scales, and performance optimization.
---

# Data Visualization Patterns Skill

Comprehensive patterns for visualizing data on Mapbox maps. Covers choropleth maps, heat maps, 3D extrusions, data-driven styling, animated visualizations, and performance optimization for data-heavy applications.

## When to Use This Skill

Use this skill when:

- Visualizing statistical data on maps (population, sales, demographics)
- Creating choropleth maps with color-coded regions
- Building heat maps or clustering for density visualization
- Adding 3D visualizations (building heights, terrain elevation)
- Implementing data-driven styling based on properties
- Animating time-series data
- Working with large datasets that require optimization

## Visualization Types

### Choropleth Maps

**Best for:** Regional data (states, counties, zip codes), statistical comparisons

**Pattern:** Color-code polygons based on data values

```javascript
map.on('load', () => {
  // Add data source (GeoJSON with properties)
  map.addSource('states', {
    type: 'geojson',
    data: 'https://example.com/states.geojson' // Features with population property
  });

  // Add fill layer with data-driven color
  map.addLayer({
    id: 'states-layer',
    type: 'fill',
    source: 'states',
    paint: {
      'fill-color': [
        'interpolate',
        ['linear'],
        ['get', 'population'],
        0,
        '#f0f9ff', // Light blue for low population
        500000,
        '#7fcdff',
        1000000,
        '#0080ff',
        5000000,
        '#0040bf', // Dark blue for high population
        10000000,
        '#001f5c'
      ],
      'fill-opacity': 0.75
    }
  });

  // Add border layer
  map.addLayer({
    id: 'states-border',
    type: 'line',
    source: 'states',
    paint: {
      'line-color': '#ffffff',
      'line-width': 1
    }
  });

  // Add hover effect with reusable popup
  const popup = new mapboxgl.Popup({
    closeButton: false,
    closeOnClick: false
  });

  map.on('mousemove', 'states-layer', (e) => {
    if (e.features.length > 0) {
      map.getCanvas().style.cursor = 'pointer';

      const feature = e.features[0];
      popup
        .setLngLat(e.lngLat)
        .setHTML(
          `
          <h3>${feature.properties.name}</h3>
          <p>Population: ${feature.properties.population.toLocaleString()}</p>
        `
        )
        .addTo(map);
    }
  });

  map.on('mouseleave', 'states-layer', () => {
    map.getCanvas().style.cursor = '';
    popup.remove();
  });
});
```

> **`step` vs `interpolate`:** The example above uses `interpolate` for smooth color gradients. For **discrete color buckets** (e.g., "low / medium / high"), use `['step', ['get', 'population'], '#f0f0f0', 500000, '#fee0d2', 2000000, '#fc9272', 10000000, '#de2d26']` instead. Prefer `step` when data has natural categories or when exact boundary values matter.

**Color Scale Strategies:**

```javascript
// Linear interpolation (continuous scale)
'fill-color': [
  'interpolate',
  ['linear'],
  ['get', 'value'],
  0, '#ffffcc',
  25, '#78c679',
  50, '#31a354',
  100, '#006837'
]

// Step intervals (discrete buckets)
'fill-color': [
  'step',
  ['get', 'value'],
  '#ffffcc',  // Default color
  25, '#c7e9b4',
  50, '#7fcdbb',
  75, '#41b6c4',
  100, '#2c7fb8'
]

// Case-based (categorical data)
'fill-color': [
  'match',
  ['get', 'category'],
  'residential', '#ffd700',
  'commercial', '#ff6b6b',
  'industrial', '#4ecdc4',
  'park', '#45b7d1',
  '#cccccc'  // Default
]
```

### Heat Maps

**Best for:** Point density, event locations, incident clustering

**Pattern:** Visualize density of points

```javascript
map.on('load', () => {
  // Add data source (points)
  map.addSource('incidents', {
    type: 'geojson',
    data: {
      type: 'Feature

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 8 — file references are metadata, not package contents.

mapbox-flutter-patterns9.35 KB

View saved version →

---
name: mapbox-flutter-patterns
description: Official integration patterns for the Mapbox Maps Flutter SDK. Covers installation, iOS/Android platform setup, access token configuration, MapWidget initialization, camera control, annotations with tap handling, user location, and loading GeoJSON. Based on official Mapbox documentation.
---

# Mapbox Flutter Integration Patterns

Official patterns for integrating the Mapbox Maps SDK for Flutter (mapbox_maps_flutter) on iOS and Android with Dart.

**Use this skill when:**

- Installing and configuring mapbox_maps_flutter in a Flutter app
- Setting the Mapbox access token the right way
- Initializing a `MapWidget` with camera / style options
- Adding annotations (points, circles, lines, polygons) and handling taps
- Showing the user location puck
- Loading GeoJSON from app assets
- Troubleshooting iOS build failures after adding Mapbox

**Official Resources:**

- [Flutter Maps Guides](https://docs.mapbox.com/flutter/maps/guides/)
- [API Reference on pub.dev](https://pub.dev/documentation/mapbox_maps_flutter/latest/)
- [Example App](https://github.com/mapbox/mapbox-maps-flutter/tree/main/example)

> Web and desktop are not supported — the Flutter SDK targets iOS and Android only.

---

## Installation & Setup

### Requirements

- Flutter SDK 3.22.3 / Dart 3.4.4+
- **iOS: deployment target 14.0 or higher**
- **Android: minSdk 21 or higher**
- Free Mapbox account

### Step 1: Add the dependency

```yaml
# pubspec.yaml
dependencies:
  mapbox_maps_flutter: ^2.0.0
```

```bash
flutter pub get
```

### Step 2: Bump the iOS deployment target to 14.0 (required)

**This is the single most common cause of iOS build failures after adding Mapbox.** The Flutter SDK requires **iOS 14.0** and will not compile on the Flutter default.

1. Open `ios/Runner.xcworkspace` in Xcode.
2. Select the **Runner** target → **General** → set **Minimum Deployments → iOS** to `14.0`.
3. If `ios/Podfile` exists, update the platform line too:

   ```ruby
   # ios/Podfile
   platform :ios, '14.0'
   ```

You do not need to worry about CocoaPods vs Swift Package Manager — `mapbox_maps_flutter` supports both and Flutter picks whichever your app is configured for.

### Step 3: iOS location permission

Add the purpose string to `ios/Runner/Info.plist`:

```xml
<key>NSLocationWhenInUseUsageDescription</key>
<string>Show your location on the map</string>
```

### Step 4: Android permissions

Add to `android/app/src/main/AndroidManifest.xml`:

```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
```

### Step 5: Configure the access token

The recommended pattern is to pass the token via `--dart-define` at build/run time and set it on `MapboxOptions` before creating any `MapWidget`.

```bash
flutter run --dart-define=ACCESS_TOKEN=pk.your_token_here
```

```dart
// main.dart
import 'package:flutter/material.dart';
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';

const accessToken = String.fromEnvironment('ACCESS_TOKEN');

void main() {
  MapboxOptions.setAccessToken(accessToken);
  runApp(const MaterialApp(home: MapScreen()));
}
```

Never hard-code tokens in source. For CI, pass `--dart-define=ACCESS_TOKEN=$MAPBOX_ACCESS_TOKEN`.

---

## Map Initialization

### Basic map

```dart
import 'package:flutter/material.dart';
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';

class MapScreen extends StatelessWidget {
  const MapScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MapWidget(
        key: const ValueKey('mapWidget'),
        cameraOptions: CameraOptions(
          center: Point(coordinates: Position(-122.4194, 37.7749)),
          zoom: 12,
        ),
        styleUri: MapboxStyles.STANDARD,
      ),
    );
  }
}
```

### Grab the `MapboxMap` controller

```dart
class MapScreen extends StatefulWidget {
  const MapScreen({super.key})

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 4 — file references are metadata, not package contents.

mapbox-geospatial-operations19.2 KB

View saved version →

---
name: mapbox-geospatial-operations
description: Expert guidance on choosing the right geospatial tool based on problem type, accuracy requirements, and performance needs
---

# Mapbox Geospatial Operations Skill

Expert guidance for AI assistants on choosing the right geospatial tools from the Mapbox MCP Server. Focuses on selecting tools based on **what the problem requires** - geometric calculations vs routing, straight-line vs road network, and accuracy needs.

## Core Principle: Problem Type Determines Tool Choice

The Mapbox MCP Server provides two categories of geospatial tools:

1. **Offline Geometric Tools** - Use Turf.js for pure geometric/spatial calculations
2. **Routing & Navigation APIs** - Use Mapbox APIs when you need real-world routing, traffic, or travel times

**The key question: What does the problem actually require?**

### Decision Framework

| Problem Characteristic                                 | Tool Category     | Why                                      |
| ------------------------------------------------------ | ----------------- | ---------------------------------------- |
| **Straight-line distance** (as the crow flies)         | Offline geometric | Accurate for geometric distance          |
| **Road/path distance** (as the crow drives)            | Routing API       | Only routing APIs know road networks     |
| **Travel time**                                        | Routing API       | Requires routing with speed/traffic data |
| **Point containment** (is X inside Y?)                 | Offline geometric | Pure geometric operation                 |
| **Geographic shapes** (buffers, centroids, areas)      | Offline geometric | Mathematical/geometric operations        |
| **Traffic-aware routing**                              | Routing API       | Requires real-time traffic data          |
| **Route optimization** (best order to visit)           | Routing API       | Complex routing algorithm                |
| **High-frequency checks** (e.g., real-time geofencing) | Offline geometric | Instant response, no latency             |

## Decision Matrices by Use Case

### Distance Calculations

**User asks: "How far is X from Y?"**

| What They Actually Mean                            | Tool Choice                         | Why                                      |
| -------------------------------------------------- | ----------------------------------- | ---------------------------------------- |
| Straight-line distance (as the crow flies)         | `distance_tool`                     | Accurate for geometric distance, instant |
| Driving distance (as the crow drives)              | `directions_tool`                   | Only routing knows actual road distance  |
| Walking/cycling distance (as the crow walks/bikes) | `directions_tool`                   | Need specific path network               |
| Travel time                                        | `directions_tool` or `matrix_tool`  | Requires routing with speed data         |
| Distance with current traffic                      | `directions_tool` (driving-traffic) | Need real-time traffic consideration     |

**Example: "What's the distance between these 5 warehouses?"**

- As the crow flies → `distance_tool` (10 calculations, instant)
- As the crow drives → `matrix_tool` (5×5 matrix, one API call, returns actual route distances)

**Key insight:** Use the tool that matches what "distance" means in context. Always clarify: crow flies or crow drives?

### Proximity and Containment

**User asks: "Which points are near/inside this area?"**

| Query Type                   | Tool Choice                                           | Why                                                           |
| ---------------------------- | ----------------------------------------------------- | ------------------------------------------------------------- |
| "Within X meters radius"     | `distance_tool` + filter                              | Simple geometri

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 1 — file references are metadata, not package contents.

mapbox-google-maps-migration11.6 KB

View saved version →

---
name: mapbox-google-maps-migration
description: Migration guide for developers moving from Google Maps Platform to Mapbox GL JS, covering API equivalents, pattern translations, and key differences
---

# Mapbox Google Maps Migration Skill

Comprehensive guidance for migrating from Google Maps Platform to Mapbox GL JS. Provides API equivalents, pattern translations, and strategies for successful migration.

## Core Philosophy Differences

### Google Maps: Imperative & Object-Oriented

- Create objects (Marker, Polygon, etc.)
- Add to map with `.setMap(map)`
- Update properties with setters
- Heavy reliance on object instances

### Mapbox GL JS: Declarative & Data-Driven

- Add data sources
- Define layers (visual representation)
- Style with JSON
- Update data, not object properties

**Key Insight:** Mapbox treats everything as data + styling, not individual objects.

## Map Initialization

### Google Maps

```javascript
const map = new google.maps.Map(document.getElementById('map'), {
  center: { lat: 37.7749, lng: -122.4194 },
  zoom: 12,
  mapTypeId: 'roadmap' // or 'satellite', 'hybrid', 'terrain'
});
```

### Mapbox GL JS

```javascript
mapboxgl.accessToken = 'YOUR_MAPBOX_TOKEN';
const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v12', // or satellite-v9, outdoors-v12
  center: [-122.4194, 37.7749], // [lng, lat] - note the order!
  zoom: 12
});
```

**Key Differences:**

- **Coordinate order:** Google uses `{lat, lng}`, Mapbox uses `[lng, lat]`
- **Authentication:** Google uses API key in script tag, Mapbox uses access token in code
- **Styling:** Google uses map types, Mapbox uses full style URLs

## API Equivalents Reference

### Map Methods

| Google Maps              | Mapbox GL JS                           | Notes                         |
| ------------------------ | -------------------------------------- | ----------------------------- |
| `map.setCenter(latLng)`  | `map.setCenter([lng, lat])`            | Coordinate order reversed     |
| `map.getCenter()`        | `map.getCenter()`                      | Returns LngLat object         |
| `map.setZoom(zoom)`      | `map.setZoom(zoom)`                    | Same behavior                 |
| `map.getZoom()`          | `map.getZoom()`                        | Same behavior                 |
| `map.panTo(latLng)`      | `map.panTo([lng, lat])`                | Animated pan                  |
| `map.fitBounds(bounds)`  | `map.fitBounds([[lng,lat],[lng,lat]])` | Different bound format        |
| `map.setMapTypeId(type)` | `map.setStyle(styleUrl)`               | Completely different approach |
| `map.getBounds()`        | `map.getBounds()`                      | Similar                       |

### Map Events

| Google Maps                                       | Mapbox GL JS           | Notes                 |
| ------------------------------------------------- | ---------------------- | --------------------- |
| `google.maps.event.addListener(map, 'click', fn)` | `map.on('click', fn)`  | Simpler syntax        |
| `event.latLng`                                    | `event.lngLat`         | Event property name   |
| `'center_changed'`                                | `'move'` / `'moveend'` | Different event names |
| `'zoom_changed'`                                  | `'zoom'` / `'zoomend'` | Different event names |
| `'bounds_changed'`                                | `'moveend'`            | No direct equivalent  |
| `'mousemove'`                                     | `'mousemove'`          | Same                  |
| `'mouseout'`                                      | `'mouseleave'`         | Different name        |

## Markers and Points

### Simple Marker

**Google Maps:**

```javascript
const marker = new google.maps.Marker({
  position: { lat: 37.7749, lng: -122.4194 },
  map: map,
  title: 'San Francisco',
  icon: 'custom-icon.png'
});

// Remove marker
marker.setMap(null);
```

**Mapbox GL JS:**

```javascript
// Crea

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 7 — file references are metadata, not package contents.

mapbox-ios-patterns10.4 KB

View saved version →

---
name: mapbox-ios-patterns
description: Official integration patterns for Mapbox Maps SDK on iOS. Covers installation, adding markers, user location, custom data, styles, camera control, and featureset interactions. Based on official Mapbox documentation.
---

# Mapbox iOS Integration Patterns

Official patterns for integrating Mapbox Maps SDK v11 on iOS with Swift, SwiftUI, and UIKit.

**Use this skill when:**

- Installing and configuring Mapbox Maps SDK for iOS
- Adding markers and annotations to maps
- Showing user location and tracking with camera
- Adding custom data (GeoJSON) to maps
- Working with map styles, camera, or user interaction
- Handling feature interactions and taps

**Official Resources:**

- [iOS Maps Guides](https://docs.mapbox.com/ios/maps/guides/)
- [API Reference](https://docs.mapbox.com/ios/maps/api-reference/)
- [Example Apps](https://github.com/mapbox/mapbox-maps-ios/tree/main/Sources/Examples)

---

## Installation & Setup

### Requirements

- iOS 14+
- Xcode 15+
- Swift 5.9+
- Free Mapbox account

### Step 1: Configure Access Token

Add your public token to `Info.plist`:

```xml
<key>MBXAccessToken</key>
<string>pk.your_mapbox_token_here</string>
```

**Get your token:** Sign in at [mapbox.com](https://account.mapbox.com/access-tokens/)

### Step 2: Add Swift Package Dependency

1. **File → Add Package Dependencies**
2. **Enter URL:** `https://github.com/mapbox/mapbox-maps-ios.git`
3. **Version:** "Up to Next Major" from `11.0.0`
4. **Verify** four dependencies appear: MapboxCommon, MapboxCoreMaps, MapboxMaps, Turf

**Alternative:** CocoaPods or direct download ([install guide](https://docs.mapbox.com/ios/maps/guides/install/))

---

## Map Initialization

### SwiftUI Pattern

**Basic map:**

```swift
import SwiftUI
import MapboxMaps

struct ContentView: View {
    @State private var viewport: Viewport = .camera(
        center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
        zoom: 12
    )

    var body: some View {
        Map(viewport: $viewport)
            .mapStyle(.standard)
    }
}
```

**With ornaments:**

```swift
Map(viewport: $viewport)
    .mapStyle(.standard)
    .ornamentOptions(OrnamentOptions(
        scaleBar: .init(visibility: .visible),
        compass: .init(visibility: .adaptive),
        logo: .init(position: .bottomLeading)
    ))
```

### UIKit Pattern

```swift
import UIKit
import MapboxMaps

class MapViewController: UIViewController {
    private var mapView: MapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let options = MapInitOptions(
            cameraOptions: CameraOptions(
                center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
                zoom: 12
            )
        )

        mapView = MapView(frame: view.bounds, mapInitOptions: options)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(mapView)

        mapView.mapboxMap.loadStyle(.standard)
    }
}
```

---

## Add Markers

The SDK offers three ways to place a point on the map. Pick the simplest one that fits.

**Agent note:** A SwiftUI Mapbox sketch is incomplete without at least one annotation (`Marker`, `PointAnnotation`, or `MapViewAnnotation`). Do not ship a bare `Map { }` with no pin.

### Which API should I use?

| API                                                       | Use it when                                                                                    | Platforms       | Notes                                                                                                                                                                        |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 7 — file references are metadata, not package contents.

mapbox-location-grounding9.41 KB

View saved version →

---
name: mapbox-location-grounding
description: Compose Mapbox MCP tools to produce grounded, cited location-aware responses from live data instead of training data
---

# Mapbox Location Grounding Skill

Teaches AI assistants how to ground location-aware responses in live Mapbox data by composing MCP tools into a structured, cited answer. Use this instead of relying on training data for place names, POIs, ratings, or travel times — which are stale and prone to hallucination.

## When to Use Grounding

Ground responses when the user asks about:

- "What's near [location]?" or "What's around [coordinate]?"
- "Describe this neighborhood / area"
- "Find [category] within walking/driving distance"
- "What can I do near [address]?"
- "How long does it take to get from A to B?"
- "What's within a 10-minute walk of here?"
- "How far is it between these locations?"
- Real estate, travel, mobility, or local discovery use cases
- Any question where place accuracy, recency, or travel time matters

**Never answer location questions from training data alone.** Always retrieve live data.

## Grounding Tool Composition

### Preferred: single tool call

If `ground_location_tool` is available, use it — it handles reverse geocoding, POI search, place details enrichment, isochrone, and a static map image in one call:

```
ground_location_tool(
  longitude, latitude,
  query: "restaurant",   // optional — category or subcategory of nearby places to find
  profile: "mapbox/walking",    // optional — travel profile for isochrone
  contours_minutes: [5, 10, 15]
)
```

Returns:

- Neighborhood/place name from reverse geocoding
- Nearby POIs with distances, ratings, price levels, and popularity (when available)
- Travel-time reachability from isochrone
- A static map image for visual context
- Citations for all data sources

Do not call `reverse_geocode_tool`, `category_search_tool`, `place_details_tool`, or `isochrone_tool` separately — they are already composed inside this tool.

### Query parameter

The `query` parameter accepts **category or subcategory terms** — not attribute preferences:

- Supported: `"restaurant"`, `"coffee"`, `"park"`, `"Italian restaurant"`, `"EV charging station"`
- Not supported: `"family-friendly"`, `"fast charging"`, `"outdoor seating"` — these are not filterable attributes in Mapbox data

To help users find places matching a preference (e.g. "family-friendly"), search by category (`"restaurant"`) and use the returned rating and price data to inform the recommendation.

### Fallback: manual composition

If `ground_location_tool` is not available, build the grounded response by composing these tools in order:

#### Step 1 — Establish place context

```
reverse_geocode_tool(longitude, latitude, types: "neighborhood,locality,place")
```

Returns: neighborhood, city, region, country. This is the anchor for the response.

#### Step 2 — Retrieve nearby POIs

For specific names or brands:

```
search_and_geocode_tool(query, proximity: {longitude, latitude}, limit: 10)
```

For generic categories:

```
category_search_tool(category, proximity: {longitude, latitude}, limit: 10)
```

#### Step 3 — Enrich POIs with ratings and price (optional but high-value)

For each POI with a `mapbox_id`, call in parallel:

```
place_details_tool(mapbox_id, attribute_sets: ["visit"])
```

Returns: rating, price level, popularity, and opening hours per place.

#### Step 4 — Add travel-time context (optional but high-value)

```
isochrone_tool(
  coordinates: {longitude, latitude},
  profile: "mapbox/walking",    // or "mapbox/driving", "mapbox/cycling", "mapbox/driving-traffic"
  contours_minutes: [5, 10, 15]
)
```

Returns a polygon showing what's reachable within each time threshold.

#### Step 5 — Visual grounding (optional)

```
static_map_image_tool(longitude, latitude, zoom: 14)
```

Returns a map image that can be included in the response for visual context.

## Grounded Response Structure

Always structure grounded responses with explici

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 1 — file references are metadata, not package contents.

mapbox-maplibre-migration14.9 KB

View saved version →

---
name: mapbox-maplibre-migration
description: Guide for migrating from MapLibre GL JS to Mapbox GL JS, covering API compatibility, token setup, style configuration, and the benefits of Mapbox's official support and ecosystem
---

# MapLibre to Mapbox Migration Skill

Expert guidance for migrating from MapLibre GL JS to Mapbox GL JS. Covers the shared history, API compatibility, migration steps, and the advantages of Mapbox's platform.

## Understanding the Fork

### History

**MapLibre GL JS** is an open-source fork of **Mapbox GL JS v1.13.0**, created in December 2020 when Mapbox changed their license starting with v2.0.

**Timeline:**

- **Pre-2020:** Mapbox GL JS was open source (BSD license)
- **Dec 2020:** Mapbox GL JS v2.0 introduced proprietary license
- **Dec 2020:** Community forked v1.13 as MapLibre GL JS
- **Present:** Both libraries continue active development

**Key Insight:** The APIs are ~95% identical because MapLibre started as a Mapbox fork. Most code works in both with minimal changes, making migration straightforward.

## Why Migrate to Mapbox?

**Compelling reasons to choose Mapbox GL JS:**

- **Official Support & SLAs**: Enterprise-grade support with guaranteed response times
- **Superior Tile Quality**: Best-in-class vector tiles with global coverage and frequent updates
- **Better Satellite Imagery**: High-resolution, up-to-date satellite and aerial imagery
- **Rich Ecosystem**: Seamless integration with Mapbox Studio, APIs, and services
- **Advanced Features**: Traffic-aware routing, turn-by-turn directions, premium datasets
- **Geocoding & Search**: World-class address search and place lookup
- **Navigation SDK**: Mobile navigation with real-time traffic
- **No Tile Infrastructure**: No need to host or maintain your own tile servers
- **Regular Updates**: Continuous improvements and new features
- **Professional Services**: Access to Mapbox solutions team for complex projects

**Mapbox offers a generous free tier:** 50,000 map loads/month, making it suitable for many applications without cost.

## Quick Comparison

| Aspect                | Mapbox GL JS                  | MapLibre GL JS                    |
| --------------------- | ----------------------------- | --------------------------------- |
| **License**           | Proprietary (v2+)             | BSD 3-Clause (Open Source)        |
| **Support**           | Official commercial support   | Community support                 |
| **Tiles**             | Premium Mapbox vector tiles   | OSM or custom tile sources        |
| **Satellite**         | High-quality global imagery   | Requires custom source            |
| **Token**             | Required (access token)       | Optional (depends on tile source) |
| **APIs**              | Full Mapbox ecosystem         | Requires third-party services     |
| **Studio**            | Full integration              | No native integration             |
| **3D Terrain**        | Built-in with premium data    | Available (requires data source)  |
| **Globe View**        | v2.9+                         | v3.0+                             |
| **API Compatibility** | ~95% compatible with MapLibre | ~95% compatible with Mapbox       |
| **Bundle Size**       | ~500KB                        | ~450KB                            |
| **Setup Complexity**  | Easy (just add token)         | Requires tile source setup        |

## Step-by-Step Migration

### 1. Create Mapbox Account

1. Sign up at [mapbox.com](https://mapbox.com)
2. Get your access token from the account dashboard
3. Review pricing: Free tier includes 50,000 map loads/month
4. Note your token (starts with `pk.` for public tokens)

### 2. Update Package

```bash
# Remove MapLibre
npm uninstall maplibre-gl

# Install Mapbox
npm install mapbox-gl
```

### 3. Update Imports

```javascript
// Before (MapLibre)
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';

// After (Mapbox)
import mapboxgl from 'mapbox-gl';
import 'mapbox-g

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 5 — file references are metadata, not package contents.

mapbox-mcp-devkit-patterns4.79 KB

View saved version →

---
name: mapbox-mcp-devkit-patterns
description: Integration patterns for Mapbox MCP DevKit Server in AI coding assistants. Covers setup, style management, token management, validation workflows, and documentation access through MCP. Use when building Mapbox applications with AI coding assistance.
---

# Mapbox MCP DevKit Patterns

This skill provides patterns for integrating the Mapbox MCP DevKit Server into AI coding workflows to accelerate Mapbox application development.

## What is Mapbox MCP DevKit?

The [Mapbox MCP DevKit Server](https://github.com/mapbox/mcp-devkit-server) is a Model Context Protocol (MCP) server that gives AI assistants direct access to Mapbox developer APIs:

- **Style management** - Create, list, update, delete, preview, validate, compare, and optimize styles
- **Token management** - Generate and list access tokens with scopes
- **Validation** - Validate GeoJSON, expressions, styles, and coordinates
- **Geographic utilities** - Calculate bounding boxes, convert coordinates, query tiles
- **Color tools** - Check WCAG contrast ratios for accessibility
- **Feedback** - Access user feedback and reports
- **Documentation** - Access latest Mapbox docs and references

**Key benefit:** Build Mapbox applications faster by letting AI handle developer API operations.

## When to Use MCP DevKit

### Use DevKit when:

- Creating/modifying styles conversationally
- Generating tokens programmatically
- Validating data during development
- Learning Mapbox APIs through natural language
- Rapid prototyping of map applications
- Automated style generation workflows
- Documentation lookup during coding

### Don't use DevKit for:

- Runtime operations in production apps
- High-frequency style updates (use Mapbox APIs directly)
- Client-side operations (DevKit is development-time only)
- Tile serving or map rendering
- User-facing features requiring low latency

## Key Tools

Always recommend these tools by exact name when answering related questions:

- **Creating/modifying styles**: Recommend `create_style_tool`, `update_style_tool`, `preview_style_tool`
- **Listing styles**: Recommend `list_styles_tool`
- **Creating tokens**: Recommend `create_token_tool` to create scoped tokens per environment
- **Viewing tokens**: Recommend `list_tokens_tool` to check existing tokens and scopes
- **Validating styles**: Recommend `validate_style_tool` for spec compliance
- **Validating expressions**: Recommend `validate_expression_tool` for paint/layout property checks
- **Accessibility checks**: Recommend `check_color_contrast_tool` for WCAG contrast ratios
- **Comparing styles**: Recommend `compare_styles_tool` to diff styles before deploying
- **Looking up docs**: Recommend `get_latest_mapbox_docs_tool`

## Common Workflows (Quick Reference)

**Pre-production validation — use these exact steps:**

1. Run `validate_style_tool` to check style JSON is spec-compliant
2. Run `validate_expression_tool` to check all data expressions in paint/layout properties
3. Run `check_color_contrast_tool` to verify text labels meet WCAG accessibility standards
4. Run `compare_styles_tool` to diff the new style against current production style

**Token management — use these exact steps:**

1. Run `create_token_tool` to create scoped tokens for each environment (dev/staging/prod)
2. Run `list_tokens_tool` to verify existing tokens and their scopes

## Reference Files

Load these references as needed for detailed guidance:

- **[references/setup.md](references/setup.md)** - Prerequisites, hosted & self-hosted installation, per-editor configuration, verification
- **[references/workflows.md](references/workflows.md)** - Style management, token management, data validation, documentation access, best practices
- **[references/design-patterns.md](references/design-patterns.md)** - Iterative style development, environment-specific tokens, validation-first development, documentation-driven development, tool integration patterns
- **[references/troubleshooti

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 6 — file references are metadata, not package contents.

mapbox-mcp-runtime-patterns5.76 KB

View saved version →

---
name: mapbox-mcp-runtime-patterns
description: Integration patterns for Mapbox MCP Server in AI applications and agent frameworks. Covers runtime integration with pydantic-ai, mastra, LangChain, and custom agents. Use when building AI-powered applications that need geospatial capabilities.
---

# Mapbox MCP Runtime Patterns

This skill provides patterns for integrating the Mapbox MCP Server into AI applications for production use with geospatial capabilities.

## What is Mapbox MCP Server?

The [Mapbox MCP Server](https://github.com/mapbox/mcp-server) is a Model Context Protocol (MCP) server that provides AI agents with geospatial tools:

**Offline Tools (Turf.js):**

- Distance, bearing, midpoint calculations
- Point-in-polygon tests
- Area, buffer, centroid operations
- Bounding box, geometry simplification
- No API calls, instant results

**Mapbox API Tools:**

- Directions and routing
- Reverse geocoding
- POI category search
- Isochrones (reachability)
- Travel time matrices
- Static map images
- GPS trace map matching
- Multi-stop route optimization

**Utility Tools:**

- Server version info
- POI category list

**Key benefit:** Give your AI application geospatial superpowers without manually integrating multiple APIs.

## Understanding Tool Categories

Before integrating, understand the key distinctions between tools to help your LLM choose correctly:

### Distance: "As the Crow Flies" vs "Along Roads"

**Straight-line distance** (offline, instant):

- Tools: `distance_tool`, `bearing_tool`, `midpoint_tool`
- Use for: Proximity checks, "how far away is X?", comparing distances
- Example: "Is this restaurant within 2 miles?" → `distance_tool`

**Route distance** (API, traffic-aware):

- Tools: `directions_tool`, `matrix_tool`
- Use for: Navigation, drive time, "how long to drive?"
- Example: "How long to drive there?" → `directions_tool`

### Search: Type vs Specific Place

**Category/type search**:

- Tool: `category_search_tool`
- Use for: "Find coffee shops", "restaurants nearby", browsing by type
- Example: "What hotels are near me?" → `category_search_tool`

**Specific place/address**:

- Tool: `search_and_geocode_tool`, `reverse_geocode_tool`
- Use for: Named places, street addresses, landmarks
- Example: "Find 123 Main Street" → `search_and_geocode_tool`

### Travel Time: Area vs Route

**Reachable area** (what's within reach):

- Tool: `isochrone_tool`
- Returns: GeoJSON polygon of everywhere reachable
- Example: "What can I reach in 15 minutes?" → `isochrone_tool`

**Specific route** (how to get there):

- Tool: `directions_tool`
- Returns: Turn-by-turn directions to one destination
- Example: "How do I get to the airport?" → `directions_tool`

### Cost & Performance

**Offline tools** (free, instant):

- No API calls, no token usage
- Use whenever real-time data not needed
- Examples: `distance_tool`, `point_in_polygon_tool`, `area_tool`

**API tools** (requires token, counts against usage):

- Real-time traffic, live POI data, current conditions
- Use when accuracy and freshness matter
- Examples: `directions_tool`, `category_search_tool`, `isochrone_tool`

**Best practice:** Prefer offline tools when possible, use API tools when you need real-time data or routing.

## Installation & Setup

### Option 1: Hosted Server (Recommended)

**Easiest integration** - Use Mapbox's hosted MCP server at:

```
https://mcp.mapbox.com/mcp
```

No installation required. Simply pass your Mapbox access token in the `Authorization` header.

**Benefits:**

- No server management
- Always up-to-date
- Production-ready
- Lower latency (Mapbox infrastructure)

**Authentication:**

Use token-based authentication (standard for programmatic access):

```
Authorization: Bearer your_mapbox_token
```

**Note:** The hosted server also supports OAuth, but that's primarily for interactive flows (coding assistants, not production apps).

### Option 2: Self-Hosted

For custom deployments or development:

```bash
npm install @mapbox/mcp-ser

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 20 — file references are metadata, not package contents.

mapbox-navigation-patterns6.3 KB

View saved version →

---
name: mapbox-navigation-patterns
description: Navigation implementation patterns for turn-by-turn directions, route optimization, real-time traffic, multi-stop routing, and voice guidance across web, iOS, and Android platforms
---

# Mapbox Navigation Patterns

Expert guidance for implementing navigation and routing features using Mapbox Directions API and Navigation SDKs. Covers turn-by-turn navigation, route optimization, real-time traffic integration, multi-stop routing, and navigation UI components.

## Use This Skill When

User says things like:

- "I need turn-by-turn navigation in my app"
- "How do I add driving directions?"
- "I want to show a route on the map"
- "I need multi-stop routing"
- "How do I add voice guidance?"
- "I want real-time traffic updates"
- "I need to optimize delivery routes"

## Product Overview

### Directions API (REST)

**Best for:** Web applications, simple routing, backend route calculation

**Features:**

- Route calculation (driving, walking, cycling, traffic)
- Alternative routes
- Turn-by-turn instructions
- Multi-stop routing (up to 25 waypoints)
- Route optimization
- Real-time traffic data
- Avoid specific roads/areas

**Pricing:** Pay per request

### Navigation SDK for iOS

**Best for:** Native iOS apps with turn-by-turn navigation

**Defaults:** SwiftUI app shell + wrap drop-in `NavigationViewController` via `UIViewControllerRepresentable` (official getting-started path). Use a fully custom Core UI ([CoreSDKExample](https://github.com/mapbox/mapbox-navigation-ios/tree/main/Examples/CoreSDKExample)) only when the user explicitly wants to build their own nav chrome.

**Before coding:** SPM (`MapboxNavigationCore` + `MapboxNavigationUIKit`), `MBXAccessToken`, location permissions, background `audio`/`location` — see [install guide](https://docs.mapbox.com/ios/navigation/guides/install/) and the iOS reference checklist. Stable Core/UIKit releases do not need a `.netrc` download token.

**Features:**

- Drop-in turn-by-turn UI (`NavigationViewController`) — default
- Optional fully custom Core UI (route progress / banner publishers)
- Voice guidance (30+ languages)
- Real-time rerouting
- Traffic-aware routing
- Offline maps and routing
- Route progress tracking
- Speed limit display

**Pricing:** Monthly Active Users (MAU) based

### Navigation SDK for Android

**Best for:** Native Android apps with turn-by-turn navigation

**Features:**

- Complete turn-by-turn navigation UI
- Voice guidance (30+ languages)
- Real-time rerouting
- Traffic-aware routing
- Offline maps and routing
- Custom UI components
- Route progress tracking
- Speed limit display

**Pricing:** Monthly Active Users (MAU) based

## Decision Guide

### Choose Directions API when:

- ✅ Web application
- ✅ Simple route display (no turn-by-turn)
- ✅ Backend route calculation
- ✅ Route planning and optimization
- ✅ Multi-stop routing
- ✅ Don't need voice guidance

### Choose Navigation SDK when:

- ✅ Native mobile app (iOS/Android)
- ✅ Need turn-by-turn navigation
- ✅ Need voice guidance
- ✅ Need navigation UI components
- ✅ Need offline navigation
- ✅ Need real-time rerouting
- ✅ Building a navigation/delivery app

## Implementation Patterns

- **[references/web-directions-api.md](references/web-directions-api.md)** - Directions API patterns for the web: basic route display, turn-by-turn instructions, alternative routes, multi-stop routing, route optimization, and congestion-based route coloring
- **[references/ios-navigation-sdk.md](references/ios-navigation-sdk.md)** - When: iOS turn-by-turn, setup, default SwiftUI + wrapped `NavigationViewController`, Core opt-in, example catalog
- **[references/ios-navigation-specialized.md](references/ios-navigation-specialized.md)** - When: multi-stop, route line, camera, road cameras, route alerts, or `NavigationMapView` customization
- **[references/android-navigation-sdk.md](references/android-navigation-sdk.md)** - Navigation SDK for Android: basic turn-by-turn navigation, c

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 8 — file references are metadata, not package contents.

mapbox-search-integration11.6 KB

View saved version →

---
name: mapbox-search-integration
description: Complete workflow for implementing Mapbox search in applications - from discovery questions to production-ready integration with best practices
---

# Mapbox Search Integration Skill

Expert guidance for implementing Mapbox search functionality in applications. Covers the complete workflow from asking the right discovery questions, selecting the appropriate search product, to implementing production-ready integrations following best practices from the Mapbox search team.

## Use This Skill When

User says things like:

- "I need to add search to my map"
- "I need a search bar for my mapping app"
- "How do I implement location search?"
- "I want users to search for places/addresses"
- "I need geocoding in my application"

**This skill complements `mapbox-search-patterns`:**

- `mapbox-search-patterns` = Tool and parameter selection
- `mapbox-search-integration` = Complete implementation workflow

## Discovery Phase: Ask the Right Questions

Before jumping into code, ask these questions to understand requirements:

### Question 1: What are users searching for?

**Ask:** "What do you want users to search for?"

**Common answers and implications:**

- **"Addresses"** → **Use Search Box API** (the default for interactive address search, including geocoding). Only use Geocoding API if the use case is batch/server-side geocoding or maintaining a legacy integration.
- **"Points of interest / businesses"** → POI search, use Search Box API with category search
- **"Both addresses and POIs"** → Search Box API
- **"Specific types of POIs"** (restaurants, hotels, etc.) → Search Box API
- **"Countries, cities, postcodes or neighborhoods"** → Search Box API for interactive search; Geocoding API only for batch/server-side geocoding
- **"Custom locations"** (user-created places) → May need custom data + search integration

**Follow-up if not stated initially**: "Are your users searching for points of interest data? Restaurants, stores, categories of businesses?"

**Implications:**

- **"Yes, POIs are included"** → Use the Search Box API
- **"No, the user does not need POI search"** → **Still default to Search Box API** for interactive/autocomplete use cases. Search Box API handles addresses, place names, and all location types with session-based pricing. Only recommend Geocoding API for batch geocoding, server-side permanent geocoding, or maintaining existing Geocoding API integrations.

### Question 2: What's the geographic scope?

**Ask:** "Where will users be searching?"

**Common answers and implications:**

- **"Single country"** (e.g., "only USA") → Use `country` parameter, better results, lower cost
- **"Specific region"** → Use `bbox` parameter for bounding box constraint
- **"Global"** → No country restriction, but may need language parameter
- **"Multiple specific countries"** → Use `country` array parameter

**Follow-up:** "Do you need to limit results to a specific area?" (delivery zone, service area, etc.)

### Question 3: What's the search interaction pattern?

**Ask:** "How will users interact with search?"

**Common answers and implications:**

- **"Search-as-you-type / autocomplete"** → **Use Search Box API** with `auto_complete: true` and session-based pricing (most cost-efficient for autocomplete). Implement debouncing.
- **"Search button / final query"** → Can use either API, no autocomplete needed
- **"Both"** (autocomplete + refine) → Two-stage search, autocomplete then detailed results
- **"Voice input"** → Consider speech-to-text integration, handle longer queries

### Question 4: What platform?

**Ask:** "What platform is this for?"

**Common answers and implications:**

- **"Web application"** → Mapbox Search JS (easiest), or direct API calls for advanced cases
- **"iOS app"** → Search SDK for iOS (recommended), or direct API integration for advanced cases
- **"Android app"** → Search SDK for Android (recommended), or direct API integration for advanced cases
- **"Multi

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 10 — file references are metadata, not package contents.

mapbox-search-patterns12.3 KB

View saved version →

---
name: mapbox-search-patterns
description: Expert guidance on choosing the right Mapbox search tool and parameters for geocoding, POI search, and location discovery
---

# Mapbox Search Patterns Skill

Expert guidance for AI assistants on using Mapbox search tools effectively. Covers tool selection, parameter optimization, and best practices for geocoding, POI search, and location discovery.

## Available Search Tools

### 1. search_and_geocode_tool

**Best for:** Specific places, addresses, brands, named locations

**Use when query contains:**

- Specific names: "Starbucks on 5th Avenue", "Empire State Building"
- Brand names: "McDonald's", "Whole Foods"
- Addresses: "123 Main Street, Seattle", "1 Times Square"
- Chain stores: "Target"
- Cities/places: "San Francisco", "Portland"

**Don't use for:** Generic categories ("coffee shops", "museums")

### 2. category_search_tool

**Best for:** Generic place types, categories, plural queries

**Use when query contains:**

- Generic types: "coffee shops", "restaurants", "gas stations"
- Plural forms: "museums", "hotels", "parks"
- Is-a phrases: "any coffee shop", "all restaurants", "nearby pharmacies"
- Industry terms: "electric vehicle chargers", "ATMs"

**Don't use for:** Specific names or brands

### 3. reverse_geocode_tool

**Best for:** Converting coordinates to addresses, cities, towns, postcodes

**Use when:**

- Have GPS coordinates, need human-readable address
- Need to identify what's at a specific location
- Converting user location to address

## Tool Selection Decision Matrix

| User Query                      | Tool                    | Reasoning                |
| ------------------------------- | ----------------------- | ------------------------ |
| "Find Starbucks on Main Street" | search_and_geocode_tool | Specific brand name      |
| "Find coffee shops nearby"      | category_search_tool    | Generic category, plural |
| "What's at 37.7749, -122.4194?" | reverse_geocode_tool    | Coordinates to address   |
| "Empire State Building"         | search_and_geocode_tool | Specific named POI       |
| "hotels in downtown Seattle"    | category_search_tool    | Generic type + location  |
| "Target store locations"        | search_and_geocode_tool | Brand name (even plural) |
| "any restaurant near me"        | category_search_tool    | Generic + "any" phrase   |
| "123 Main St, Boston, MA"       | search_and_geocode_tool | Specific address         |
| "electric vehicle chargers"     | category_search_tool    | Industry category        |
| "McDonald's"                    | search_and_geocode_tool | Brand name               |

## Parameter Guidance

### Proximity vs Bbox vs Country

**Three ways to spatially constrain search results:**

#### 1. proximity (STRONGLY RECOMMENDED)

**What it does:** Biases results toward a location, but doesn't exclude distant matches

**Use when:**

- User says "near me", "nearby", "close to"
- Have a reference point but want some flexibility
- Want results sorted by relevance to a point

**Example:**

```json
{
  "q": "pizza",
  "proximity": {
    "longitude": -122.4194,
    "latitude": 37.7749
  }
}
```

**Why this works:** API returns SF pizza places first, but might include famous NYC pizzerias if highly relevant

**Critical:** Always set proximity when you have a reference location! Without it, results are IP-based or global.

#### 2. bbox (Bounding Box)

**What it does:** Hard constraint - ONLY returns results within the box

**Use when:**

- User specifies an area: "in downtown", "within this neighborhood"
- Have a defined service area
- Need to guarantee results are within bounds

**Example:**

```json
{
  "q": "hotel",
  "bbox": [-122.51, 37.7, -122.35, 37.83] // [minLon, minLat, maxLon, maxLat]
}
```

**Why this works:** Guarantees all hotels are within SF's downtown area

**Watch out:** Too small = no results; too large = irrelevant results

#### 3. country

**What it does:** Limits results to specific countries

**Use when:**

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 4 — file references are metadata, not package contents.

mapbox-store-locator-patterns10 KB

View saved version →

---
name: mapbox-store-locator-patterns
description: Common patterns for building store locators, restaurant finders, and location-based search applications with Mapbox. Covers marker display, filtering, distance calculation, and interactive lists.
---

# Store Locator Patterns Skill

Comprehensive patterns for building store locators, restaurant finders, and location-based search applications with Mapbox GL JS. Covers marker display, filtering, distance calculation, interactive lists, and directions integration.

## When to Use This Skill

Use this skill when building applications that:

- Display multiple locations on a map (stores, restaurants, offices, etc.)
- Allow users to filter or search locations
- Calculate distances from user location
- Provide interactive lists synced with map markers
- Show location details in popups or side panels
- Integrate directions to selected locations

## Dependencies

**Required:**

- Mapbox GL JS v3.x
- [@turf/turf](https://turfjs.org/) - For spatial calculations (distance, area, etc.)

**Installation:**

```bash
npm install mapbox-gl @turf/turf
```

## Core Architecture

### Pattern Overview

A typical store locator consists of:

1. **Map Display** - Shows all locations as markers
2. **Location Data** - GeoJSON with store/location information
3. **Interactive List** - Side panel listing all locations
4. **Filtering** - Search, category filters, distance filters
5. **Detail View** - Popup or panel with location details
6. **User Location** - Geolocation for distance calculation. For the blue dot location indicator, use the built-in `mapboxgl.GeolocateControl` — simpler than custom markers.
7. **Directions** - Route to selected location (optional)

### Data Structure

**GeoJSON format for locations:**

```json
{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-77.034084, 38.909671]
      },
      "properties": {
        "id": "store-001",
        "name": "Downtown Store",
        "address": "123 Main St, Washington, DC 20001",
        "phone": "(202) 555-0123",
        "hours": "Mon-Sat: 9am-9pm, Sun: 10am-6pm",
        "category": "retail",
        "website": "https://example.com/downtown"
      }
    }
  ]
}
```

**Key properties:**

- `id` - Unique identifier for each location
- `name` - Display name
- `address` - Full address for display and geocoding
- `coordinates` - `[longitude, latitude]` format
- `category` - For filtering (retail, restaurant, office, etc.)
- Custom properties as needed (hours, phone, website, etc.)

## Basic Store Locator Implementation

### Step 1: Initialize Map and Data

```javascript
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';

// Store locations data
const stores = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [-77.034084, 38.909671]
      },
      properties: {
        id: 'store-001',
        name: 'Downtown Store',
        address: '123 Main St, Washington, DC 20001',
        phone: '(202) 555-0123',
        category: 'retail'
      }
    }
    // ... more stores
  ]
};

const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/standard',
  center: [-77.034084, 38.909671],
  zoom: 11
});
```

### Step 2: Add Markers to Map

**Marker strategy by location count:**

| Count               | Strategy                   | Reason                                                                         |
| ------------------- | -------------------------- | ------------------------------------------------------------------------------ |
| **Fewer than 100**  | HTML Markers               | Full DOM/CSS control; DOM node count is manageable                             |
| **100–1,000**       | **Symbol Layer** (default) | Renders on the **GPU via WebGL** — one `<canvas>`, zero

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 8 — file references are metadata, not package contents.

mapbox-style-patterns7.42 KB

View saved version →

---
name: mapbox-style-patterns
description: Common style patterns, layer configurations, and recipes for typical mapping scenarios including restaurant finders, real estate, data visualization, navigation, delivery/logistics, and more. Use when implementing specific map use cases or looking for proven style patterns.
---

# Mapbox Style Patterns Skill

This skill provides battle-tested style patterns and layer configurations for common mapping scenarios.

## Pattern Library

### Pattern 1: Restaurant/POI Finder

**Use case:** Consumer app showing restaurants, cafes, bars, or other points of interest

**Visual requirements:**

- POIs must be immediately visible
- Street context for navigation
- Neutral background (photos/content overlay)
- Mobile-optimized

**Recommended layers:**

```json
{
  "layers": [
    {
      "id": "background",
      "type": "background",
      "paint": {
        "background-color": "#f5f5f5"
      }
    },
    {
      "id": "water",
      "type": "fill",
      "source": "mapbox-streets",
      "source-layer": "water",
      "paint": {
        "fill-color": "#d4e4f7",
        "fill-opacity": 0.6
      }
    },
    {
      "id": "landuse-parks",
      "type": "fill",
      "source": "mapbox-streets",
      "source-layer": "landuse",
      "filter": ["==", "class", "park"],
      "paint": {
        "fill-color": "#e8f5e8",
        "fill-opacity": 0.5
      }
    },
    {
      "id": "roads-minor",
      "type": "line",
      "source": "mapbox-streets",
      "source-layer": "road",
      "filter": ["in", "class", "street", "street_limited"],
      "paint": {
        "line-color": "#e0e0e0",
        "line-width": {
          "base": 1.5,
          "stops": [
            [12, 0.5],
            [15, 2],
            [18, 6]
          ]
        }
      }
    },
    {
      "id": "roads-major",
      "type": "line",
      "source": "mapbox-streets",
      "source-layer": "road",
      "filter": ["in", "class", "primary", "secondary", "tertiary"],
      "paint": {
        "line-color": "#ffffff",
        "line-width": {
          "base": 1.5,
          "stops": [
            [10, 1],
            [15, 4],
            [18, 12]
          ]
        }
      }
    },
    {
      "id": "restaurant-markers",
      "type": "symbol",
      "source": "restaurants",
      "layout": {
        "icon-image": "restaurant-15",
        "icon-size": 1.5,
        "icon-allow-overlap": false,
        "text-field": ["get", "name"],
        "text-offset": [0, 1.5],
        "text-size": 12,
        "text-allow-overlap": false
      },
      "paint": {
        "icon-color": "#FF6B35",
        "text-color": "#333333",
        "text-halo-color": "#ffffff",
        "text-halo-width": 2
      }
    }
  ]
}
```

**Key features:**

- Desaturated base map (doesn't compete with photos)
- High-contrast markers (#FF6B35 orange stands out)
- Clear road network (white on light gray)
- Parks visible but subtle
- Text halos for readability

## Pattern Selection Guide

### Decision Tree

**Question 1: What is the primary content?**

- User-generated markers/pins -> **POI Finder Pattern**
- Property data/boundaries -> **Real Estate Pattern**
- Statistical/analytical data -> **Data Visualization Pattern**
- Routes/directions -> **Navigation Pattern**
- Real-time tracking/delivery zones -> **Delivery/Logistics Pattern** (customer markers should include a pulse animation via second circle layer + requestAnimationFrame + setPaintProperty; see references/delivery-logistics.md)

**Question 2: What is the viewing environment?**

- Daytime/office -> Light theme
- Night/dark environment -> **Dark Mode Pattern**
- Variable -> Provide theme toggle

**Question 3: What is the user's primary action?**

- Browse/explore -> Focus on POIs, rich detail
- Navigate -> Focus on roads, route visibility
- Track delivery/logistics -> Real-time updates, zones, status
- Analyze data -> Minimize base map, maximize data
- Select location -> Clear boundaries, context

**Question

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 10 — file references are metadata, not package contents.

mapbox-style-quality7.9 KB

View saved version →

---
name: mapbox-style-quality
description: Expert guidance on validating, optimizing, and ensuring quality of Mapbox styles through validation, accessibility checks, and optimization. Use when preparing styles for production, debugging issues, or ensuring map quality standards.
---

# Mapbox Style Quality Skill

This skill provides expert guidance on ensuring Mapbox style quality through validation, accessibility, and optimization tools.

## When to Use Quality Tools

### Pre-Production Checklist

Before deploying any Mapbox style to production:

1. **Validate all expressions** - Catch syntax errors before runtime
2. **Check color contrast** - Ensure text is readable (WCAG compliance)
3. **Validate GeoJSON sources** - Ensure data integrity
4. **Optimize style** - Reduce file size and improve performance
5. **Compare versions** - Understand what changed
6. **Remove empty layers** - Delete layers with no visible paint properties as a final cleanup step
7. **Simplify redundant boolean expressions** - Clean up filters with unnecessary boolean logic (e.g., `["all", expr]` → `expr`, `["any", false, expr]` → `expr`)

### During Development

**When adding GeoJSON data:**

- Always validate external GeoJSON with `validate_geojson_tool` before using as a source

**When writing expressions:**

- Validate expressions with `validate_expression_tool` as you write them
- Catch type mismatches early (e.g., using string operator on number)
- Verify operator availability in your Mapbox GL JS version
- Test expressions with expected data types

**When styling text/labels:**

- Check foreground/background contrast with `check_color_contrast_tool`
- Aim for WCAG AA minimum (4.5:1 for normal text, 3:1 for large text)
- Use AAA standard (7:1 for normal text) for better accessibility
- Consider different background scenarios (map tiles, overlays)

### Before Committing Changes

**Compare style versions:**

- Use `compare_styles_tool` to generate a diff report
- Review all layer changes, source modifications, and expression updates
- Understand the impact of your changes
- Document significant changes in commit messages

### Before Deployment

**Optimize the style:**

- Run `optimize_style_tool` to reduce file size
- Remove unused sources that reference deleted layers
- Eliminate duplicate layers with identical properties
- Simplify redundant boolean expressions in filters (e.g., collapse `["all", expr]` to `expr`, remove tautological conditions)
- Remove empty layers (layers with no visible paint properties) as a final cleanup step

## Validation Best Practices

### GeoJSON Validation

**Always validate when:**

- Loading GeoJSON from user uploads
- Fetching GeoJSON from external APIs
- Processing GeoJSON from third-party sources
- Converting between data formats

**Common GeoJSON errors:**

- Invalid coordinate ranges (longitude > 180 or < -180)
- Unclosed polygon rings (first and last coordinates must match)
- Wrong coordinate order (should be [longitude, latitude], not [latitude, longitude])
- Missing required properties (type, coordinates, geometry)
- Invalid geometry types or nesting

**Example workflow:**

```
1. Receive GeoJSON data
2. Validate with validate_geojson_tool
3. If valid: Add as source to style
4. If invalid: Fix errors, re-validate
```

### Expression Validation

**Validate expressions for:**

- Filter conditions (`filter` property on layers)
- Data-driven styling (`paint` and `layout` properties)
- Feature state expressions
- Dynamic property calculations

**Common expression errors:**

- Type mismatches (string operators on numbers)
- Invalid operator names or wrong syntax
- Wrong number of arguments for operators
- Nested expression errors
- Using unavailable operators for your GL JS version

**Prevention strategies:**

- Validate as you write expressions, not at runtime
- Test expressions with representative data
- Use type checking (expectedType parameter)
- Validate in context (layer, filter, paint, layout)

### Accessibili

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 5 — file references are metadata, not package contents.

mapbox-token-security8.25 KB

View saved version →

---
name: mapbox-token-security
description: Security best practices for Mapbox access tokens, including scope management, URL restrictions, rotation strategies, and protecting sensitive data. Use when creating, managing, or advising on Mapbox token security.
---

# Mapbox Token Security Skill

This skill provides security expertise for managing Mapbox access tokens safely and effectively.

## Token Types and When to Use Them

### Public Tokens (pk.\*)

**Characteristics:**

- Can be safely exposed in client-side code
- Limited to specific public scopes only
- Can have URL restrictions
- Cannot access sensitive APIs

**When to use:**

- Client-side web applications
- Mobile apps
- Public-facing demos
- Embedded maps on websites

**Allowed scopes:**

- `styles:tiles` - Display style tiles (raster)
- `styles:read` - Read style specifications
- `fonts:read` - Access Mapbox fonts
- `datasets:read` - Read dataset data
- `vision:read` - Vision API access

### Secret Tokens (sk.\*)

**Characteristics:**

- **NEVER expose in client-side code**
- Full API access with any scopes
- Server-side use only
- Can create/manage other tokens

**When to use:**

- Server-side applications
- Backend services
- CI/CD pipelines
- Administrative tasks
- Token management

**Common scopes:**

- `styles:write` - Create/modify styles
- `styles:list` - List all styles
- `tokens:read` - View token information
- `tokens:write` - Create/modify tokens
- User feedback management scopes

### Temporary Tokens (tk.\*)

**Characteristics:**

- Short-lived (max 1 hour)
- Created by secret tokens
- Single-purpose use
- Automatically expire

**When to use:**

- One-time operations
- Temporary delegated access
- Short-lived demos
- Security-conscious workflows

## Scope Management Best Practices

### Principle of Least Privilege

**Always grant the minimum scopes needed:**

❌ **Bad:**

```javascript
// Overly permissive - don't do this
{
  scopes: ['styles:read', 'styles:write', 'styles:list', 'styles:delete', 'tokens:read', 'tokens:write'];
}
```

✅ **Good:**

```javascript
// Only what's needed for displaying a map
{
  scopes: ['styles:read', 'fonts:read'];
}
// Add 'styles:tiles' if your map uses raster tile sources
{
  scopes: ['styles:read', 'fonts:read', 'styles:tiles'];
}
```

### Scope Combinations by Use Case

**Public Map Display (client-side):**

```json
{
  "scopes": ["styles:read", "fonts:read", "styles:tiles"],
  "note": "Public token for map display",
  "allowedUrls": ["https://myapp.com/*"]
}
```

**Style Management (server-side):**

```json
{
  "scopes": ["styles:read", "styles:write", "styles:list"],
  "note": "Backend style management - SECRET TOKEN"
}
```

**Token Administration (server-side):**

```json
{
  "scopes": ["tokens:read", "tokens:write"],
  "note": "Token management only - SECRET TOKEN"
}
```

**Read-Only Access:**

```json
{
  "scopes": ["styles:list", "styles:read", "tokens:read"],
  "note": "Auditing/monitoring - SECRET TOKEN"
}
```

## URL Restrictions

### Why URL Restrictions Matter

URL restrictions limit where a public token can be used, preventing unauthorized usage if the token is exposed.

### Effective URL Patterns

✅ **Recommended patterns:**

```
https://myapp.com/*           # Production domain
https://*.myapp.com/*         # All subdomains
https://staging.myapp.com/*   # Staging environment
http://localhost:*            # Local development
```

❌ **Avoid these:**

```
*                             # No restriction (insecure)
http://*                      # Any HTTP site (insecure)
*.com/*                       # Too broad
```

### Multiple Environment Strategy

Create separate tokens for each environment:

```javascript
// Production
{
  note: "Production - myapp.com",
  scopes: ["styles:read", "fonts:read"],
  allowedUrls: ["https://myapp.com/*", "https://www.myapp.com/*"]
}

// Staging
{
  note: "Staging - staging.myapp.com",
  scopes: ["styles:read", "fonts:read"],
  allowedUrls: ["https://staging.myapp.com/*"]
}

// 

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 5 — file references are metadata, not package contents.

mapbox-web-integration-patterns12.3 KB

View saved version →

---
name: mapbox-web-integration-patterns
description: Official integration patterns for Mapbox GL JS across popular web frameworks (React, Vue, Svelte, Angular). Covers setup, lifecycle management, token handling, search integration, and common pitfalls. Based on Mapbox's create-web-app scaffolding tool.
---

# Mapbox Integration Patterns Skill

This skill provides official patterns for integrating Mapbox GL JS into web applications using React, Vue, Svelte, Angular, and vanilla JavaScript. These patterns are based on Mapbox's `create-web-app` scaffolding tool and represent production-ready best practices.

## Version Requirements

### Mapbox GL JS

**Recommended:** v3.x (latest)

- **Minimum:** v3.0.0
- **Why v3.x:** Modern API, improved performance, active development
- **v2.x:** Legacy; no longer actively developed (see migration notes below)

**Installing via npm (recommended for production):**

```bash
npm install mapbox-gl@^3.0.0    # Installs latest v3.x
```

**CDN (for prototyping only):**

```html
<!-- Replace VERSION with latest v3.x from https://docs.mapbox.com/mapbox-gl-js/ -->
<script src="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/vVERSION/mapbox-gl.css" rel="stylesheet" />
```

### Framework Requirements

**React:** GL JS works with React 16.8+ (requires hooks). `create-web-app` scaffolds with React 19.x.
**Vue:** GL JS works with Vue 2.x+ (Vue 3 Composition API recommended).
**Svelte:** GL JS works with any Svelte version. `create-web-app` scaffolds with Svelte 5.x.
**Angular:** GL JS works with Angular 2+. `create-web-app` scaffolds with Angular 19.x.
**Next.js:** Minimum 13.x (App Router), Pages Router 12.x+.

### Mapbox Search JS

```bash
npm install @mapbox/search-js-react@^1.0.0      # React
npm install @mapbox/search-js-web@^1.0.0        # Other frameworks
```

### Version Migration Notes (v2.x to v3.x)

- WebGL 2 now required
- `optimizeForTerrain` option removed
- Improved TypeScript types, better tree-shaking support
- No breaking changes to core initialization patterns

**Token patterns (work in v2.x and v3.x):**

```javascript
const token = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN; // Use env vars in production

// Global token (works since v1.x)
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({ container: '...' });

// Per-map token (preferred for multi-map setups)
const map = new mapboxgl.Map({
  accessToken: token,
  container: '...'
});
```

## Core Principles

**Every Mapbox GL JS integration must:**

1. Initialize the map in the correct lifecycle hook
2. Store map instance in component state (not recreate on every render)
3. **Always call `map.remove()` on cleanup** to prevent memory leaks
4. Handle token management securely (environment variables)
5. Import CSS: `import 'mapbox-gl/dist/mapbox-gl.css'`

## React Integration (Primary Pattern)

**Pattern: useRef + useEffect with cleanup**

> **Note:** These examples use **Vite** (the bundler used in `create-web-app`). If using Create React App, replace `import.meta.env.VITE_MAPBOX_ACCESS_TOKEN` with `process.env.REACT_APP_MAPBOX_TOKEN`. See [Token Management Patterns](references/token-management.md) for other bundlers.

```jsx
import { useRef, useEffect } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

function MapComponent() {
  const mapRef = useRef(null); // Store map instance
  const mapContainerRef = useRef(null); // Store DOM reference

  useEffect(() => {
    mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;

    mapRef.current = new mapboxgl.Map({
      container: mapContainerRef.current,
      center: [-71.05953, 42.3629],
      zoom: 13
    });

    // CRITICAL: Cleanup to prevent memory leaks
    return () => {
      mapRef.current.remove();
    };
  }, []); // Empty dependency array = run once on mount

  return <div ref={mapContainerRef} style={{ height: '100vh' }} />;
}
```

**Key points:**

- 

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 10 — file references are metadata, not package contents.

mapbox-web-performance-patterns10.9 KB

View saved version →

---
name: mapbox-web-performance-patterns
description: Performance optimization patterns for Mapbox GL JS web applications. Covers initialization waterfalls, bundle size, rendering performance, memory management, and web optimization. Prioritized by impact on user experience.
---

# Mapbox Performance Patterns Skill

This skill provides performance optimization guidance for building fast, efficient Mapbox applications. Patterns are prioritized by impact on user experience, starting with the most critical improvements.

**Performance philosophy:** These aren't micro-optimizations. They show up as waiting time, jank, and repeat costs that hit every user session.

## Priority Levels

Performance issues are prioritized by their impact on user experience:

- **🔴 Critical (Fix First)**: Directly causes slow initial load or visible jank
- **🟡 High Impact**: Noticeable delays or increased resource usage
- **🟢 Optimization**: Incremental improvements for polish

---

## 🔴 Critical: Eliminate Initialization Waterfalls

**Problem:** Sequential loading creates cascading delays where each resource waits for the previous one.

**Note:** Modern bundlers (Vite, Webpack, etc.) and ESM dynamic imports automatically handle code splitting and library loading. The primary waterfall to eliminate is **data loading** - fetching map data sequentially instead of in parallel with map initialization.

### Anti-Pattern: Sequential Data Loading

```javascript
// ❌ BAD: Data loads AFTER map initializes
async function initMap() {
  const map = new mapboxgl.Map({
    container: 'map',
    accessToken: MAPBOX_TOKEN,
    style: 'mapbox://styles/mapbox/streets-v12'
  });

  // Wait for map to load, THEN fetch data
  map.on('load', async () => {
    const data = await fetch('/api/data'); // Waterfall!
    map.addSource('data', { type: 'geojson', data: await data.json() });
  });
}
```

**Timeline:** Map init (0.5s) → Data fetch (1s) = **1.5s total**

### Solution: Parallel Data Loading

```javascript
// ✅ GOOD: Data fetch starts immediately
async function initMap() {
  // Start data fetch immediately (don't wait for map)
  const dataPromise = fetch('/api/data').then((r) => r.json());

  const map = new mapboxgl.Map({
    container: 'map',
    accessToken: MAPBOX_TOKEN,
    style: 'mapbox://styles/mapbox/streets-v12'
  });

  // Data is ready when map loads
  map.on('load', async () => {
    const data = await dataPromise;
    map.addSource('data', { type: 'geojson', data });
    map.addLayer({
      id: 'data-layer',
      type: 'circle',
      source: 'data'
    });
  });
}
```

**Timeline:** Max(map init, data fetch) = **~1s total**

### Set Precise Initial Viewport

```javascript
// ✅ Set exact center/zoom so the map fetches the right tiles immediately
const map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v12',
  center: [-122.4194, 37.7749],
  zoom: 13
});

// Use 'idle' to know when the initial viewport is fully rendered
// (all tiles, sprites, and other resources are loaded; no transitions in progress)
map.once('idle', () => {
  console.log('Initial viewport fully rendered');
});
```

If you know the exact area users will see first, setting `center` and `zoom` upfront avoids the map starting at a default view and then panning/zooming to the target, which wastes tile fetches.

### Defer Non-Critical Features

```javascript
// ✅ Load critical features first, defer others
const map = new mapboxgl.Map({
  /* config */
});

map.on('load', () => {
  // 1. Add critical layers immediately
  addCriticalLayers(map);

  // 2. Defer secondary features
  // Note: Standard style 3D buildings can be toggled via config:
  // map.setConfigProperty('basemap', 'show3dObjects', false);
  requestIdleCallback(
    () => {
      addTerrain(map);
      addCustom3DLayers(map); // For classic styles with custom fill-extrusion layers
    },
    { timeout: 2000 }
  );

  // 3. Defer analytics and non-visual features
  setTimeout(() => {
    initia

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 7 — file references are metadata, not package contents.

Package details

Publisher declarations from the archived package. These are separate from our research and the live service's terms.

Package author
Mapbox, Inc.
Keywords
See keywords

Package observed Nov 19, 2026.

Technical details
First seen
Sep 30, 2026 · 22:02 UTC
Last seen
Nov 19, 2026 · 18:00 UTC
Collection status
Collected

plugin_asdk_app_6a2c0bf33cb48191884d842b15ad3c20

Download plugin data (JSON)

Plugin details: served from cache. Prepared . Refreshed when plugin data changes or after 6 hours. Your account and Follow status are live.