К основному содержанию
скилл CX Codex

mapbox-store-locator-patterns — скилл для Claude Code

Паттерны для поиска заведений на карте через Mapbox GL JS. Скилл учит агента выводить маркеры через WebGL, фильтровать точки и считать расстояния с @turf/turf.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add mapbox/mapbox-agent-skills --skill mapbox-store-locator-patterns -a claude-code
Открыть на GitHub

Что делает mapbox-store-locator-patterns

Скилл даёт правила для построения интерактивных карт локаторов заведений и офисов. Он описывает структуру GeoJSON с координатами точек и связку карты со списком объектов. Для отображения синей точки текущей геопозиции пользователя предлагается встроенный элемент mapboxgl.GeolocateControl.

Подход к маркерам зависит от объёма данных. Если точек меньше 100, применяются маркеры HTML. Для диапазона от 100 до 1000 точек скилл настраивает слой symbol, который отрисовывается на GPU через WebGL без нагрузки на DOM дерева документа. Если объектов больше 1000, подключается кластеризация.

Для работы проекта требуются пакеты mapbox-gl версии v3.x и @turf/turf, а клики по точкам рекомендуется вешать через map.addInteraction. Без действующего токена Mapbox карта не загрузится.

Какие задачи решает

  • настроить отображение точек на карте через слой symbol в WebGL
  • связать интерактивный список заведений с маркерами на карте
  • рассчитать расстояние до объектов с помощью библиотеки @turf/turf
  • выбрать стратегию отрисовки меток в зависимости от их количества

Примеры запросов агенту

  • Сделай карту филиалов на Mapbox GL JS с боковой панелью списка и расчётом расстояний через turf
  • Добавь слой symbol для магазинов из GeoJSON и настрой клики через addInteraction
  • Покажи текущее местоположение пользователя на карте через GeolocateControl

Как установить mapbox-store-locator-patterns

1Через Skills CLI (Vercel)

npx skills add mapbox/mapbox-agent-skills --skill mapbox-store-locator-patterns -a claude-code

2Вручную: положить файлы

~/.claude/skills/mapbox-store-locator-patterns/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/mapbox-store-locator-patterns/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора18

mapbox-style-quality Скилл проверяет стили Mapbox перед релизом: валидирует выражения и GeoJSON, считает контраст текста по WCAG, оптимизирует файл стиля. CX Codex +1 2 000установок mapbox-search-integration Проводит агента через весь цикл внедрения поиска Mapbox: от вопросов о задаче до готового кода с нужным API и параметрами. CX Codex +1 1 900установок mapbox-token-security Набор правил безопасности для токенов Mapbox: разграничение публичных и секретных ключей, ограничение по URL и защита от тихих падений карты. CX Codex +1 1 900установок mapbox-search-patterns Подсказывает агенту, какой инструмент поиска Mapbox выбрать и какие параметры выставить для геокодинга, поиска POI и адресов. CX Codex +1 1 800установок mapbox-ios-patterns Официальные шаблоны интеграции Mapbox Maps SDK v11 в iOS-приложения на Swift, SwiftUI и UIKit. Пригодится, когда нужно добавить карту, маркеры или геоданные. CX Codex +1 1 500установок mapbox-mcp-devkit-patterns Скилл описывает, как подключить Mapbox MCP DevKit Server к ИИ-ассистенту и работать со стилями, токенами и валидацией прямо в чате. CX Codex +1 1 500установок mapbox-maplibre-migration Ведёт миграцию с MapLibre GL JS на Mapbox GL JS: замена пакета, импортов, стилей и токена. Пригодится, если упираетесь в свои тайлы или нужна официальная поддержка. CX Codex +1 1 400установок mapbox-mcp-runtime-patterns Скилл учит агента подключать Mapbox MCP Server к ИИ-приложениям. Он помогает модели выбирать между расчётами Turf.js и сетевыми API маршрутизации. CX Codex +1 1 400установок

Похожие

maplibre-mapbox-migration maplibre Помогает перевести веб-приложение с Mapbox GL JS на открытую библиотеку MapLibre GL JS. Пригодится при отказе от коммерческой лицензии и смене источников тайлов. CX Codex +1 464установок threejs-fundamentals CloudAI-X Помогает настроить базовую сцену Three.js r186: рендерер, камеры, цикл анимации с THREE.Timer и import map для WebGL или WebGPU с TSL. CX Codex +1 17 400установок threejs-interaction CloudAI-X Скилл учит агента настраивать выбор объектов, перемещение по плоскости и управление камерой в three.js для WebGL и WebGPU. CX Codex +1 14 300установок game-engine официальный github Помогает GitHub Copilot создавать браузерные игры и игровые движки на HTML5 и JavaScript. Подходит для 2D, 3D, физики, коллизий и управления. 13 140установок threejs-scene-setup gamedev-skills Настраивает базовую сцену three.js и помогает найти причины пустого или чёрного canvas. Нужен при старте проекта, ресайзе, цикле рендеринга и OrbitControls. CX Codex +1 5 500установок webgl-3d-object MengTo Добавляет в агент правила генерации трёхмерных объектов на Three.js с честным PBR-освещением, тенями и анимацией вместо псевдо-3D на CSS. CX Codex +1 1 600установок

Рядом в теме «Фронтенд и UI»

Всё по теме «Фронтенд и UI» →

Вопросы о mapbox-store-locator-patterns

Как установить mapbox-store-locator-patterns в Claude Code?

Выполните команду npx skills add mapbox/mapbox-agent-skills --skill mapbox-store-locator-patterns -a claude-code.

Что делает mapbox-store-locator-patterns?

Скилл предоставляет агенту архитектурные шаблоны для создания локаторов магазинов, включая отрисовку маркеров, работу со списками и пространственные расчёты.

Какие зависимости нужны для работы с кодом из скилла?

В проекте понадобятся библиотеки mapbox-gl версии v3.x и @turf/turf, которые устанавливаются через команду npm install mapbox-gl @turf/turf.

Исходный текст

SKILL.md · MIT
---
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 per-point DOM elements |
| **More than 1,000** | Clustering                 | Reduces visual clutter at large scale                                          |

> HTML Markers create one DOM element per point. Beyond ~100 locations the browser spends too much time on layout/paint. Symbol layers bypass the DOM entirely — the GPU draws all points in a single WebGL draw call.

**Symbol Layer implementation** (best for 100–1,000 locations). For HTML Markers (fewer than 100) or Clustering (more than 1,000), see `references/markers.md`.

```javascript
map.on('load', () => {
  // Add store data as source
  map.addSource('stores', {
    type: 'geojson',
    data: stores
  });

  // Add custom marker image
  map.loadImage('/marker-icon.png', (error, image) => {
    if (error) throw error;
    map.addImage('custom-marker', image);

    // Add symbol layer
    map.addLayer({
      id: 'stores-layer',
      type: 'symbol',
      source: 'stores',
      layout: {
        'icon-image': 'custom-marker',
        'icon-size': 0.8,
        'icon-allow-overlap': true,
        'text-field': ['get', 'name'],
        'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
        'text-offset': [0, 1.5],
        'text-anchor': 'top',
        'text-size': 12
      }
    });
  });

  // Handle marker clicks using Interactions API (recommended)
  map.addInteraction('store-click', {
    type: 'click',
    target: { layerId: 'stores-layer' },
    handler: (e) => {
      const store = e.feature;
      flyToStore(store);
      createPopup(store);
    }
  });

  // Or using traditional event listener:
  // map.on('click', 'stores-layer', (e) => {
  //   const store = e.features[0];
  //   flyToStore(store);
  //   createPopup(store);
  // });
  //
  // For why addInteraction is preferred over map.on(), and how to pair it with
  // setFeatureState/appearances for hover and selection styling, see the
  // "interactions" reference file in the mapbox-style-patterns skill.

  // Change cursor on hover
  map.on('mouseenter', 'stores-layer', () => {
    map.getCanvas().style.cursor = 'pointer';
  });

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

### Step 3: Build Interactive Location List

```javascript
function buildLocationList(stores) {
  const listingContainer = document.getElementById('listings');

  stores.features.forEach((store, index) => {
    const listing = listingContainer.appendChild(document.createElement('div'));
    listing.id = `listing-${store.properties.id}`;
    listing.className = 'listing';

    const link = listing.appendChild(document.createElement('a'));
    link.href = '#';
    link.className = 'title';
    link.id = `link-${store.properties.id}`;
    link.innerHTML = store.properties.name;

    const details = listing.appendChild(document.createElement('div'));
    details.innerHTML = `
      <p>${store.properties.address}</p>
      <p>${store.properties.phone || ''}</p>
    `;

    // Handle listing click
    link.addEventListener('click', (e) => {
      e.preventDefault();
      flyToStore(store);
      createPopup(store);
      highlightListing(store.properties.id);
    });
  });
}

function flyToStore(store) {
  map.flyTo({
    center: store.geometry.coordinates,
    zoom: 15,
    duration: 1000
  });
}

function createPopup(store) {
  const popups = document.getElementsByClassName('mapboxgl-popup');
  // Remove existing popups
  if (popups[0]) popups[0].remove();

  new mapboxgl.Popup({ closeOnClick: true })
    .setLngLat(store.geometry.coordinates)
    .setHTML(
      `<h3>${store.properties.name}</h3>
       <p>${store.properties.address}</p>
       <p>${store.properties.phone}</p>
       ${store.properties.website ? `<a href="${store.properties.website}" target="_blank">Visit Website</a>` : ''}`
    )
    .addTo(map);
}

// IMPORTANT: highlightListing MUST include scrollIntoView — without it,
// selecting a marker on the map won't scroll the sidebar to the listing.
function highlightListing(id) {
  // Remove existing highlights
  const activeItem = document.getElementsByClassName('active');
  if (activeItem[0]) {
    activeItem[0].classList.remove('active');
  }

  // Add highlight to selected listing
  const listing = document.getElementById(`listing-${id}`);
  listing.classList.add('active');

  // Scroll the selected listing into view (critical UX requirement)
  listing.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// Build the list on load
map.on('load', () => {
  buildLocationList(stores);
});
```

## Reference Files

Load these references for additional patterns as needed:

| Reference                 | File                                   | Contents                                                         |
| ------------------------- | -------------------------------------- | ---------------------------------------------------------------- |
| HTML Markers & Clustering | `references/markers.md`                | HTML Markers (< 100 locations), Clustering (> 1000 locations)    |
| Search & Filter           | `references/search-filter.md`          | Text search, category filter                                     |
| Geolocation & Directions  | `references/geolocation-directions.md` | User location, distance calculation, route directions            |
| Styling & Layout          | `references/styling-layout.md`         | Full HTML/CSS layout, custom marker CSS                          |
| Performance & A11y        | `references/optimization-a11y.md`      | Debounced search, data management, error handling, accessibility |
| Variations & React        | `references/variations-react.md`       | Mobile-first, fullscreen, map-only, React implementation         |

## Resources

- [Turf.js](https://turfjs.org/) - Spatial analysis library (recommended for distance calculations)
- [Mapbox GL JS API](https://docs.mapbox.com/mapbox-gl-js/)
- [Interactions API Guide](https://docs.mapbox.com/mapbox-gl-js/guides/user-interactions/interactions/)
- [GeoJSON Specification](https://geojson.org/)
- [Directions API](https://docs.mapbox.com/api/navigation/directions/)
- [Store Locator Tutorial](https://docs.mapbox.com/help/tutorials/building-a-store-locator/)

© mapbox · MIT · mapbox/mapbox-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой