Token导航 LogoToken导航

Agent Skill · 研究检索

mapbox-integration-patterns(Mapbox 集成模式)

mapbox-integration-patterns 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

mapbox-integration-patterns 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证为 MIT,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 37,152。

总安装 1,787周安装 73GitHub Stars 44下载 578核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
MIT

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:mapbox-integration-patterns(Mapbox 集成模式)
来源仓库:https://github.com/mapbox/mcp-devkit-server
仓库路径:skills/mapbox-integration-patterns
安装命令:
npx skills add https://github.com/mapbox/mcp-devkit-server --skill mapbox-integration-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/mapbox/mcp-devkit-server --skill mapbox-integration-patterns

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中快速定位候选结果。支持基于关键词、任务场景或来源线索进行信息检索与筛选。通过 npx skills add 命令从 GitHub 仓库安装使用。建议确认权限范围和维护状态,避免触发联网或文件读写操作。

mapbox-integration-patterns 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/mapbox-integration-patterns

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/mapbox/mcp-devkit-server --skill mapbox-integr…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

mapbox-integration-patterns 怎么安装?

在终端执行 npx skills add https://github.com/mapbox/mcp-devkit-server --skill mapbox-integration-patt…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

mapbox-integration-patterns 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

mapbox-integration-patterns 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

mapbox-integration-patterns 是免费的吗?

来源标注的许可证是 MIT。本站不代收任何费用,也不托管安装包;能否商用、要不要署名,以许可证原文为准。

mapbox-integration-patterns 用的人多吗?

公开数据是累计安装 1,787 次,近一周安装 73 次,下载 578 次,GitHub 44 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

mapbox-integration-patterns 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 3 个目录同时收录,说明这个 Skill 流传比较广。
  • 许可证明确为 MIT,商用和分发边界好判断。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。
  • 需要许可证清楚、并且有第三方扫描结果的团队项目。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
mapbox-integration-patterns

Mapbox 集成模式 · 本页

1,78744接触敏感数据MIT通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Mapbox Integration Patterns Skill

This skill provides official patterns for integrating Mapbox GL JS into web applications across different frameworks. 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: Still supported but deprecated patterns (see migration notes below)

Installing via npm (recommended for production):

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

CDN (for prototyping only):

<!-- 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"
/>

⚠️ Production apps should use npm, not CDN - ensures consistent versions and offline builds.

Framework Requirements

React:

  • Minimum: 19+ (current implementation in create-web-app)
  • Recommended: Latest 19.x

Vue:

  • Minimum: 3.x (Composition API recommended)
  • Vue 2.x: Use Options API pattern (mounted/unmounted hooks)

Svelte:

  • Minimum: 5+ (current implementation in create-web-app)
  • Recommended: Latest 5.x

Angular:

  • Minimum: 19+ (current implementation in create-web-app)
  • Recommended: Latest 19.x

Next.js:

  • Minimum: 13.x (App Router)
  • Pages Router: 12.x+

Mapbox Search JS

Required for search integration:

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

Version Migration Notes

Migrating from v2.x to v3.x:

  • accessToken can now be passed to Map constructor (preferred)
  • Improved TypeScript types
  • Better tree-shaking support
  • No breaking changes to core initialization patterns

Example:

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

// v2.x pattern (still works in v3.x)
mapboxgl.accessToken = token;
const map = new mapboxgl.Map({ container: '...' });

// v3.x pattern (preferred)
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'

Framework-Specific Patterns

React Integration

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 the Token Management Patterns section for other bundlers.
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:

  • Use useRef for both map instance and container
  • Initialize in useEffect with empty deps []
  • Always return cleanup function that calls map.remove()
  • Never initialize map in render (causes infinite loops)

React + Search JS:

import { useRef, useEffect, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import { SearchBox } from '@mapbox/search-js-react';
import 'mapbox-gl/dist/mapbox-gl.css';

const accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;
const center = [-71.05953, 42.3629];

function MapWithSearch() {
  const mapRef = useRef(null);
  const mapContainerRef = useRef(null);
  const [inputValue, setInputValue] = useState('');

  useEffect(() => {
    mapboxgl.accessToken = accessToken;

    mapRef.current = new mapboxgl.Map({
      container: mapContainerRef.current,
      center: center,
      zoom: 13
    });

    return () => {
      mapRef.current.remove();
    };
  }, []);

  return (
    <>
      <div
        style={{
          margin: '10px 10px 0 0',
          width: 300,
          right: 0,
          top: 0,
          position: 'absolute',
          zIndex: 10
        }}
      >
        <SearchBox
          accessToken={accessToken}
          map={mapRef.current}
          mapboxgl={mapboxgl}
          value={inputValue}
          proximity={center}
          onChange={(d) => setInputValue(d)}
          marker
        />
      </div>
      <div ref={mapContainerRef} style={{ height: '100vh' }} />
    </>
  );
}

Vue Integration

Pattern: mounted + unmounted lifecycle hooks

<template>
  <div ref="mapContainer" class="map-container"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;

export default {
  mounted() {
    const map = new mapboxgl.Map({
      container: this.$refs.mapContainer,
      style: 'mapbox://styles/mapbox/standard',
      center: [-71.05953, 42.3629],
      zoom: 13
    });

    // Assign map instance to component property
    this.map = map;
  },

  // CRITICAL: Clean up when component is unmounted
  unmounted() {
    this.map.remove();
    this.map = null;
  }
};
</script>

<style>
.map-container {
  width: 100%;
  height: 100%;
}
</style>

Key points:

  • Initialize in mounted() hook
  • Access container via this.$refs.mapContainer
  • Store map as this.map
  • Always implement unmounted() hook to call map.remove()

Svelte Integration

Pattern: onMount + onDestroy

<script>
  import { Map } from 'mapbox-gl'
  import 'mapbox-gl/dist/mapbox-gl.css'
  import { onMount, onDestroy } from 'svelte'

  let map
  let mapContainer

  onMount(() => {
    map = new Map({
      container: mapContainer,
      accessToken: import.meta.env.VITE_MAPBOX_ACCESS_TOKEN,
      center: [-71.05953, 42.36290],
      zoom: 13
    })
  })

  // CRITICAL: Clean up on component destroy
  onDestroy(() => {
    map.remove()
  })
</script>

<div class="map" bind:this={mapContainer}></div>

<style>
  .map {
    position: absolute;
    width: 100%;
    height: 100%;
  }
</style>

Key points:

  • Use onMount for initialization
  • Bind container with bind:this={mapContainer}
  • Always implement onDestroy to call map.remove()
  • Can pass accessToken directly to Map constructor in Svelte

Angular Integration

Pattern: ngOnInit + ngOnDestroy with SSR handling

import {
  Component,
  ElementRef,
  OnDestroy,
  OnInit,
  ViewChild,
  inject
} from '@angular/core';
import { isPlatformBrowser, CommonModule } from '@angular/common';
import { PLATFORM_ID } from '@angular/core';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-map',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit, OnDestroy {
  @ViewChild('mapContainer', { static: false })
  mapContainer!: ElementRef<HTMLDivElement>;

  private map: any;
  private readonly platformId = inject(PLATFORM_ID);

  async ngOnInit(): Promise<void> {
    // IMPORTANT: Check if running in browser (not SSR)
    if (!isPlatformBrowser(this.platformId)) {
      return;
    }

    try {
      await this.initializeMap();
    } catch (error) {
      console.error('Failed to initialize map:', error);
    }
  }

  private async initializeMap(): Promise<void> {
    // Dynamically import to avoid SSR issues
    const mapboxgl = (await import('mapbox-gl')).default;

    this.map = new mapboxgl.Map({
      accessToken: environment.mapboxAccessToken,
      container: this.mapContainer.nativeElement,
      center: [-71.05953, 42.3629],
      zoom: 13
    });

    // Handle map errors
    this.map.on('error', (e: any) => console.error('Map error:', e.error));
  }

  // CRITICAL: Clean up on component destroy
  ngOnDestroy(): void {
    if (this.map) {
      this.map.remove();
    }
  }
}

Template (map.component.html):

<div #mapContainer style="height: 100vh; width: 100%"></div>

Key points:

  • Use @ViewChild to reference map container
  • Check isPlatformBrowser before initializing (SSR support)
  • Dynamically import mapbox-gl to avoid SSR issues
  • Initialize in ngOnInit() lifecycle hook
  • Always implement ngOnDestroy() to call map.remove()
  • Handle errors with map.on('error',...)

Vanilla JavaScript (with Vite)

Pattern: Module imports with initialization function

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

// Set access token
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;

let map;

/**
 * Initialize the map
 */
function initMap() {
  map = new mapboxgl.Map({
    container: 'map-container',
    center: [-71.05953, 42.3629],
    zoom: 13
  });

  map.on('load', () => {
    console.log('Map is loaded');
  });
}

// Initialize when script runs
initMap();

HTML:

<div id="map-container" style="height: 100vh;"></div>

Key points:

  • Store map in module-scoped variable
  • Initialize immediately or on DOMContentLoaded
  • Listen for 'load' event for post-initialization actions

Vanilla JavaScript (No Bundler - CDN)

Pattern: Script tag with inline initialization

⚠️ Note: This pattern is for prototyping only. Production apps should use npm/bundler for version control and offline builds.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mapbox GL JS - No Bundler</title>

    <!-- Mapbox GL JS CSS -->
    <!-- Replace 3.x.x with latest version from https://docs.mapbox.com/mapbox-gl-js/ -->
    <link
      href="https://api.mapbox.com/mapbox-gl-js/v3.x.x/mapbox-gl.css"
      rel="stylesheet"
    />

    <style>
      body {
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        margin: 0;
        padding: 0;
      }
      #map-container {
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map-container"></div>

    <!-- Mapbox GL JS -->
    <!-- Replace 3.x.x with latest version from https://docs.mapbox.com/mapbox-gl-js/ -->
    <script src="https://api.mapbox.com/mapbox-gl-js/v3.x.x/mapbox-gl.js"></script>

    <script>
      // Set access token
      mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN_HERE';

      let map;

      function initMap() {
        map = new mapboxgl.Map({
          container: 'map-container',
          center: [-71.05953, 42.3629],
          zoom: 13
        });

        map.on('load', () => {
          console.log('Map is loaded');
        });
      }

      // Initialize when page loads
      initMap();
    </script>
  </body>
</html>

Key points:

  • ⚠️ Prototyping only - not recommended for production
  • Replace 3.x.x with specific version (e.g., 3.7.0) from Mapbox docs
  • Don't use /latest/ - always pin to specific version for consistency
  • Initialize after script loads (bottom of body)
  • For production: Use npm + bundler instead

Why not CDN for production?

  • ❌ Network dependency (breaks offline)
  • ❌ No version locking (CDN could change)
  • ❌ Slower (no bundler optimization)
  • ❌ No tree-shaking
  • ✅ Use npm for production: npm install mapbox-gl@^3.0.0

Token Management Patterns

Environment Variables (Recommended)

Different frameworks use different prefixes for client-side environment variables:

Framework/BundlerEnvironment VariableAccess Pattern
ViteVITE_MAPBOX_ACCESS_TOKENimport.meta.env.VITE_MAPBOX_ACCESS_TOKEN
Next.jsNEXT_PUBLIC_MAPBOX_TOKENprocess.env.NEXT_PUBLIC_MAPBOX_TOKEN
Create React AppREACT_APP_MAPBOX_TOKENprocess.env.REACT_APP_MAPBOX_TOKEN
Angularenvironment.mapboxAccessTokenEnvironment files (environment.ts)

Vite.env file:

VITE_MAPBOX_ACCESS_TOKEN=pk.eyJ1...

Next.js.env.local file:

NEXT_PUBLIC_MAPBOX_TOKEN=pk.eyJ1...

Important:

  • ✅ Always use environment variables for tokens
  • ✅ Never commit .env files to version control
  • ✅ Use public tokens (pk.*) for client-side apps
  • ✅ Add .env to .gitignore
  • ✅ Provide .env.example template for team

.gitignore:

.env
.env.local
.env.*.local

.env.example:

VITE_MAPBOX_ACCESS_TOKEN=your_token_here

Mapbox Search JS Integration

Search Box Component Pattern

Install dependency:

npm install @mapbox/search-js-react      # React
npm install @mapbox/search-js-web        # Vanilla/Vue/Svelte

Note: Both packages include @mapbox/search-js-core as a dependency. You only need to install -core directly if building a custom search UI.

React Search Pattern:

import { SearchBox } from '@mapbox/search-js-react';

// Inside component:
<SearchBox
  accessToken={accessToken}
  map={mapRef.current} // Pass map instance
  mapboxgl={mapboxgl} // Pass mapboxgl library
  value={inputValue}
  onChange={(value) => setInputValue(value)}
  proximity={centerCoordinates} // Bias results near center
  marker // Show marker for selected result
/>;

Key configuration options:

  • accessToken: Your Mapbox public token
  • map: Map instance (must be initialized first)
  • mapboxgl: The mapboxgl library reference
  • proximity: [lng, lat] to bias results geographically
  • marker: Boolean to show/hide result marker
  • placeholder: Search box placeholder text

Positioning Search Box

Absolute positioning (overlay):

<div
  style={{
    position: 'absolute',
    top: 10,
    right: 10,
    zIndex: 10,
    width: 300
  }}
>
  <SearchBox {...props} />
</div>

Common positions:

  • Top-right: top: 10px, right: 10px
  • Top-left: top: 10px, left: 10px
  • Bottom-left: bottom: 10px, left: 10px

Common Mistakes to Avoid

❌ Mistake 1: Forgetting to call map.remove()

// BAD - Memory leak!
useEffect(() => {
  const map = new mapboxgl.Map({ ... })
  // No cleanup function
}, [])
// GOOD - Proper cleanup
useEffect(() => {
  const map = new mapboxgl.Map({ ... })
  return () => map.remove()  // ✅ Cleanup
}, [])

Why: Every Map instance creates WebGL contexts, event listeners, and DOM nodes. Without cleanup, these accumulate and cause memory leaks.


❌ Mistake 2: Initializing map in render

// BAD - Infinite loop in React!
function MapComponent() {
  const map = new mapboxgl.Map({ ... })  // Runs on every render
  return <div />
}
// GOOD - Initialize in effect
function MapComponent() {
  useEffect(() => {
    const map = new mapboxgl.Map({ ... })
  }, [])
  return <div />
}

Why: React components re-render frequently. Creating a new map on every render causes infinite loops and crashes.


❌ Mistake 3: Not storing map instance properly

// BAD - map variable lost between renders
function MapComponent() {
  useEffect(() => {
    let map = new mapboxgl.Map({ ... })
    // map variable is not accessible later
  }, [])
}
// GOOD - Store in useRef
function MapComponent() {
  const mapRef = useRef()
  useEffect(() => {
    mapRef.current = new mapboxgl.Map({ ... })
    // mapRef.current accessible throughout component
  }, [])
}

Why: You need to access the map instance for operations like adding layers, markers, or calling remove().


❌ Mistake 4: Wrong dependency array in useEffect

// BAD - Re-creates map on every render
useEffect(() => {
  const map = new mapboxgl.Map({ ... })
  return () => map.remove()
})  // No dependency array

// BAD - Re-creates map when props change
useEffect(() => {
  const map = new mapboxgl.Map({ center: props.center, ... })
  return () => map.remove()
}, [props.center])
// GOOD - Initialize once
useEffect(() => {
  const map = new mapboxgl.Map({ ... })
  return () => map.remove()
}, [])  // Empty array = run once

// GOOD - Update map property instead
useEffect(() => {
  if (mapRef.current) {
    mapRef.current.setCenter(props.center)
  }
}, [props.center])

Why: Map initialization is expensive. Initialize once, then use map methods to update properties.


❌ Mistake 5: Hardcoding token in source code

// BAD - Token exposed in source code
mapboxgl.accessToken = 'pk.eyJ1IjoiZXhhbXBsZSIsImEiOiJjbGV4YW1wbGUifQ.example';
// GOOD - Use environment variable
mapboxgl.accessToken = import.meta.env.VITE_MAPBOX_ACCESS_TOKEN;

Why: Tokens in source code get committed to version control and exposed publicly. Always use environment variables.


❌ Mistake 6: Not handling Angular SSR

// BAD - Crashes during server-side rendering
ngOnInit() {
  import('mapbox-gl').then(mapboxgl => {
    this.map = new mapboxgl.Map({ ... })
  })
}
// GOOD - Check platform first
ngOnInit() {
  if (!isPlatformBrowser(this.platformId)) {
    return  // Skip map init during SSR
  }

  import('mapbox-gl').then(mapboxgl => {
    this.map = new mapboxgl.Map({ ... })
  })
}

Why: Mapbox GL JS requires browser APIs (WebGL, Canvas). Angular Universal (SSR) will crash without platform check.


❌ Mistake 7: Missing CSS import

// BAD - Map renders but looks broken
import mapboxgl from 'mapbox-gl';
// Missing CSS import
// GOOD - Import CSS for proper styling
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';

Why: The CSS file contains critical styles for map controls, popups, and markers. Without it, the map appears broken.


Next.js Specific Patterns

App Router (Recommended)

'use client'  // Mark as client component

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

export default function Map() {
  const mapRef = useRef<mapboxgl.Map>()
  const mapContainerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!mapContainerRef.current) return

    mapboxgl.accessToken = process.env.NEXT_PUBLIC_MAPBOX_TOKEN!

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

    return () => mapRef.current?.remove()
  }, [])

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

Key points:

  • Must use 'use client' directive (maps require browser APIs)
  • Use process.env.NEXT_PUBLIC_* for environment variables
  • Type mapRef properly with TypeScript

Pages Router (Legacy)

import dynamic from 'next/dynamic'

// Dynamically import to disable SSR for map component
const Map = dynamic(() => import('../components/Map'), {
  ssr: false,
  loading: () => <p>Loading map...</p>
})

export default function HomePage() {
  return <Map />
}

Key points:

  • Use dynamic import with ssr: false
  • Provide loading state
  • Map component itself follows standard React pattern

Style Configuration

Default Center and Zoom Guidelines

Recommended defaults:

  • Center: [-71.05953, 42.36290] (Boston, MA) - Mapbox HQ
  • Zoom: 13 for city-level view

Zoom level guide:

  • 0-2: World view
  • 3-5: Continent/country
  • 6-9: Region/state
  • 10-12: City view
  • 13-15: Neighborhood
  • 16-18: Street level
  • 19-22: Building level

Customizing for user location:

// Use browser geolocation
if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition((position) => {
    map.setCenter([position.coords.longitude, position.coords.latitude]);
    map.setZoom(13);
  });
}

Testing Patterns

Unit Testing Maps

Mock mapbox-gl:

// vitest.config.js or jest.config.js
export default {
  setupFiles: ['./test/setup.js']
};
// test/setup.js
vi.mock('mapbox-gl', () => ({
  default: {
    Map: vi.fn(() => ({
      on: vi.fn(),
      remove: vi.fn(),
      setCenter: vi.fn(),
      setZoom: vi.fn()
    })),
    accessToken: ''
  }
}));

Why: Mapbox GL JS requires WebGL and browser APIs that don't exist in test environments. Mock the library to test component logic.


When to Use This Skill

Invoke this skill when:

  • Setting up Mapbox GL JS in a new project
  • Integrating Mapbox into a specific framework
  • Debugging map initialization issues
  • Adding Mapbox Search functionality
  • Implementing proper cleanup and lifecycle management
  • Converting between frameworks (e.g., React to Vue)
  • Reviewing code for Mapbox integration best practices

Related Skills

  • mapbox-cartography: Map design principles and styling
  • mapbox-token-security: Token management and security
  • mapbox-style-patterns: Common map style patterns

Resources

平台分布

Claude Code

30.66%
按下载量换算177

Antigravity

24.4%
按下载量换算141

Codex

16.29%
按下载量换算94

OpenCode

11.52%
按下载量换算67

Gemini CLI

7.96%
按下载量换算46

Cursor

3.29%
按下载量换算19

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

继续浏览同类 Skills