Skip to main content
skill CX Codex

large-scale-map-visualization — Claude Code skill for 100k-point maps

large-scale-map-visualization — a skill for web maps carrying tens of thousands of markers. It picks clustering libraries, viewport loading, and rendering tricks that keep the browser responsive.

MIT 240 installs ★ 274 updated 2026-10-30

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add curiositech/some_claude_skills --skill large-scale-map-visualization -a claude-code
Open on GitHub

What large-scale-map-visualization does

This skill targets maps with more than 5,000 points, up to 100,000 and beyond. It walks through the tool choice for each scale: plain Leaflet under 100 markers, react-leaflet-cluster up to 1,000, use-supercluster for the mid range, and Supercluster inside Web Workers once you pass 50,000.

The skill ships TypeScript and SQL patterns. The React side shows a useSupercluster hook that recomputes clusters on every moveend and zooms into a cluster on click via getClusterExpansionZoom. The backend side provides a PostGIS function find_in_viewport that returns only 20% of points at low zoom levels.

It also tells you what not to use it for: static map images and 3D scenes are out of scope. The author points to Mapbox Static and MapLibre GL instead.

What it helps with

  • speed up a map with thousands of markers
  • pick a clustering library for a given point count
  • load only the points inside the current viewport
  • offload clustering to Web Workers past 50k points
  • write PostGIS queries with low-zoom sampling

Example prompts for the agent

  • My map freezes with 40,000 markers, show me the Supercluster and Web Workers setup
  • Write a useSupercluster hook that expands clusters on click
  • Create a find_in_viewport PostGIS function with sampling at low zoom

How to install large-scale-map-visualization

1Skills CLI (Vercel)

npx skills add curiositech/some_claude_skills --skill large-scale-map-visualization -a claude-code

2Manually: put the files in place

~/.claude/skills/large-scale-map-visualization/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/large-scale-map-visualization/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about large-scale-map-visualization

How do I install large-scale-map-visualization in Claude Code?

Run npx skills add curiositech/some_claude_skills --skill large-scale-map-visualization -a claude-code. The skill lands in ~/.claude/skills/large-scale-map-visualization/SKILL.md.

What does large-scale-map-visualization do?

It advises on architecture for web maps with 5,000 to 100,000+ geographic points: Supercluster clustering, viewport-based loading, canvas rendering, and progressive disclosure.

Does it make sense for a map with a hundred markers?

No. The skill itself says maps under 100 markers need no optimization — vanilla Leaflet is fine. It is built for volumes starting around 5,000 points.

Source text

SKILL.md · MIT
---
name: large-scale-map-visualization
description: Master of high-performance web map implementations handling 5,000-100,000+ geographic data points. Specializes in Leaflet.js optimization, Supercluster algorithms, viewport-based loading, canvas
  rendering, and progressive disclosure UX patterns.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch
metadata:
  category: Data & Analytics
  tags:
  - maps
  - leaflet
  - geospatial
  - clustering
  - performance
  - visualization
  - supercluster
  - react
  pairs-with:
  - skill: geospatial-data-pipeline
    reason: Geospatial pipelines prepare and optimize the data that map visualizations render
  - skill: react-performance-optimizer
    reason: Rendering 100K+ markers requires React virtualization and memoization optimization
  - skill: data-viz-2025
    reason: Map visualizations combine geographic rendering with chart overlays and data tooltips
---

# Large-Scale Map Visualization Expert

Master of high-performance web map implementations handling 5,000-100,000+ geographic data points. Specializes in Leaflet.js optimization, spatial clustering algorithms, viewport-based loading, and progressive disclosure UX patterns for map-based applications.

## Activation Triggers

**Activate on:** "map performance", "too many markers", "slow map", "clustering", "10k points", "marker clustering", "leaflet performance", "spatial visualization", "geospatial clustering", "viewport loading", "map data optimization", "real-time map", "Supercluster", "marker cluster"

**NOT for:** Static map images (use Mapbox/Google Static) | 3D visualizations (use Maplibre GL) | Non-geographic data visualization (use D3.js/Chart.js) | Simple maps with <100 markers (vanilla Leaflet is fine)

## Core Expertise

### Performance Architecture

```
┌─────────────────────────────────────────────────────────────┐
│              MAP PERFORMANCE TIERS                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  0-100 markers    → Vanilla Leaflet (no optimization)      │
│  100-1,000        → Basic clustering (react-leaflet-cluster)│
│  1,000-10,000     → Supercluster + viewport loading        │
│  10,000-50,000    → Supercluster + canvas + sampling       │
│  50,000-500,000   → Web Workers + server-side clustering   │
│  500,000+         → MVT tiles + backend pre-aggregation    │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### Technology Stack Decisions

| Use Case | Best Library | Why |
|----------|--------------|-----|
| React + <5k points | `react-leaflet-cluster` | Simple drop-in, wraps Leaflet.markercluster |
| React + 5-50k points | `use-supercluster` hook | 3-5x faster, viewport-aware, GeoJSON native |
| React + 50k+ points | `supercluster` + Web Workers | Offload clustering to background thread |
| Static sites | Server-side clustering | Pre-compute at build time |
| Real-time updates | Canvas renderer + sampling | Minimize DOM manipulation |

## Key Techniques

### 1. Marker Clustering with Supercluster

**Why Supercluster beats alternatives:**
- **Performance**: Handles 500k points in 1-2 seconds vs 8+ seconds for Leaflet.markercluster
- **Architecture**: Index-based k-d tree clustering, can run server-side or in Workers
- **API**: Simple GeoJSON input/output
- **Viewport-aware**: Only clusters visible points

**Implementation Pattern:**

```tsx
import useSupercluster from "use-supercluster";

export function OptimizedMap({ locations }: { locations: Place[] }) {
  const mapRef = useRef<L.Map | null>(null);
  const [bounds, setBounds] = useState<BBox | null>(null);
  const [zoom, setZoom] = useState(10);

  // Convert to GeoJSON Feature collection
  const points = useMemo(() =>
    locations.map(place => ({
      type: "Feature" as const,
      properties: {
        cluster: false,
        placeId: place.id,
        place
      },
      geometry: {
        type: "Point" as const,
        coordinates: [place.longitude, place.latitude]
      }
    })),
    [locations]
  );

  // Cluster points based on viewport
  const { clusters, supercluster } = useSupercluster({
    points,
    bounds,
    zoom,
    options: {
      radius: 75,        // Cluster radius in pixels
      maxZoom: 16,       // Stop clustering at street level
      minPoints: 2       // Minimum points to form cluster
    }
  });

  // Update viewport on map move
  useEffect(() => {
    if (!mapRef.current) return;

    const handleMove = () => {
      const map = mapRef.current!;
      const b = map.getBounds();
      setBounds([b.getWest(), b.getSouth(), b.getEast(), b.getNorth()]);
      setZoom(map.getZoom());
    };

    mapRef.current.on("moveend", handleMove);
    handleMove(); // Initial load

    return () => mapRef.current?.off("moveend", handleMove);
  }, []);

  return (
    <MapContainer ref={mapRef} preferCanvas={true}>
      {clusters.map(cluster => {
        const [lng, lat] = cluster.geometry.coordinates;
        const { cluster: isCluster, point_count } = cluster.properties;

        if (isCluster) {
          return (
            <Marker
              key={`cluster-${cluster.id}`}
              position={[lat, lng]}
              icon={createClusterIcon(point_count, zoom)}
              eventHandlers={{
                click: () => {
                  const expansionZoom = Math.min(
                    supercluster!.getClusterExpansionZoom(cluster.id),
                    18
                  );
                  mapRef.current?.setView([lat, lng], expansionZoom, {
                    animate: true
                  });
                }
              }}
            />
          );
        }

        return (
          <PlaceMarker
            key={cluster.properties.placeId}
            place={cluster.properties.place}
          />
        );
      })}
    </MapContainer>
  );
}
```

### 2. Viewport-Based Loading (Supabase + PostGIS)

**Database Function:**

```sql
CREATE OR REPLACE FUNCTION find_in_viewport(
  min_lng DOUBLE PRECISION,
  min_lat DOUBLE PRECISION,
  max_lng DOUBLE PRECISION,
  max_lat DOUBLE PRECISION,
  zoom_level INTEGER DEFAULT 11,
  max_results INTEGER DEFAULT 10000
)
RETURNS TABLE (
  id UUID,
  name TEXT,
  latitude DOUBLE PRECISION,
  longitude DOUBLE PRECISION
  /* other fields */
) AS $$
BEGIN
  -- At low zoom levels, sample to reduce density
  IF zoom_level < 9 THEN
    RETURN QUERY
    SELECT
      p.id, p.name,
      ST_Y(p.geog::geometry) as latitude,
      ST_X(p.geog::geometry) as longitude
    FROM places p
    WHERE p.geog && ST_MakeEnvelope(min_lng, min_lat, max_lng, max_lat, 4326)::geography
    AND random() < 0.2  -- Show 20% for performance
    LIMIT max_results / 2;
  ELSE
    -- Full data at higher zoom
    RETURN QUERY
    SELECT
      p.id, p.name,
      ST_Y(p.geog::geometry) as latitude,
      ST_X(p.geog::geometry) as longitude
    FROM places p
    WHERE p.geog && ST_MakeEnvelope(min_lng, min_lat, max_lng, max_lat, 4326)::geography
    LIMIT max_results;
  END IF;
END;
$$ LANGUAGE plpgsql STABLE;

-- Ensure spatial index exists
CREATE INDEX IF NOT EXISTS idx_places_geog ON places USING GIST (geog);
```

**React Query Hook:**

```tsx
import { useQuery } from "@tanstack/react-query";
import { supabase } from "@/lib/supabase";

type BBox = [number, number, number, number]; // [west, south, east, north]

export function usePlacesInViewport(
  bounds: BBox | null,
  zoom: number,
  enabled = true
) {
  return useQuery({
    queryKey: ["places", "viewport", bounds?.join(","), zoom],
    queryFn: async () => {
      if (!bounds) return [];

      const [west, south, east, north] = bounds;

      const { data, error } = await supabase.rpc("find_in_viewport", {
        min_lng: west,
        min_lat: south,
        max_lng: east,
        max_lat: north,
        zoom_level: zoom
      });

      if (error) throw error;
      return data || [];
    },
    enabled: enabled && !!bounds,
    staleTime: 5 * 60 * 1000,    // 5 min (locations rarely change)
    gcTime: 30 * 60 * 1000,       // 30 min in cache
    refetchOnWindowFocus: false
  });
}
```

### 3. Progressive Disclosure Strategy

Show appropriate detail levels based on zoom:

```tsx
const getClusterOptions = (zoom: number) => ({
  radius: zoom < 10 ? 100 : zoom < 14 ? 75 : 50,
  maxZoom: 16,
  minPoints: zoom < 10 ? 5 : 2
});

const getMarkerSize = (zoom: number) =>
  zoom < 12 ? 24 : zoom < 15 ? 32 : 40;

const shouldShowLabel = (zoom: number) => zoom >= 14;
```

### 4. Canvas Rendering for Performance

```tsx
import L from "leaflet";

// Enable canvas renderer globally
const canvasRenderer = L.canvas({
  tolerance: 10,      // Hit detection tolerance
  padding: 0.5        // Extra render area (0.5 = 50% of viewport)
});

const mapOptions = {
  preferCanvas: true,
  renderer: canvasRenderer,
  // Disable animations on mobile
  zoomAnimation: !isMobile(),
  fadeAnimation: !isMobile(),
  markerZoomAnimation: !isMobile()
};
```

**Performance gain**: 3-5x faster rendering with 1,000+ markers

### 5. Efficient Cluster Icons

```tsx
import L from "leaflet";

// Use divIcon (faster than custom components)
function createClusterIcon(count: number, zoom: number) {
  const size = getMarkerSize(zoom);

  return L.divIcon({
    html: `
      <div style="
        width: ${size}px;
        height: ${size}px;
        background: linear-gradient(135deg, #d97706, #f59e0b);
        border-radius: 50%;
        border: 3px solid #1a1410;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: ${zoom < 12 ? '10px' : '14px'};
        box-shadow: 0 4px 12px rgba(0,0,0,0.4);
      ">
        ${count}
      </div>
    `,
    className: "cluster-icon",
    iconSize: [size, size],
    iconAnchor: [size / 2, size / 2]
  });
}
```

### 6. Debounced Map Events

```tsx
import { useDebouncedCallback } from "use-debounce";

const handleMapMove = useDebouncedCallback(() => {
  const bounds = mapRef.current?.getBounds();
  const zoom = mapRef.current?.getZoom();
  if (bounds && zoom) {
    setBounds([
      bounds.getWest(),
      bounds.getSouth(),
      bounds.getEast(),
      bounds.getNorth()
    ]);
    setZoom(zoom);
  }
}, 300); // 300ms debounce

useEffect(() => {
  mapRef.current?.on("moveend", handleMapMove);
  return () => mapRef.current?.off("moveend", handleMapMove);
}, []);
```

## Performance Benchmarks

Based on real-world testing and research (sources in references):

| Strategy | 1k points | 5k points | 10k points | Mobile (4G) |
|----------|-----------|-----------|------------|-------------|
| No clustering | 800ms | 3.5s ❌ | 8s ❌ | 12s ❌ |
| Basic clustering | 400ms | 1.8s ⚠️ | 4s ⚠️ | 6s ❌ |
| Leaflet.markercluster | 200ms | 800ms ⚠️ | 2s ⚠️ | 3s ⚠️ |
| Supercluster + viewport | 150ms ✅ | 300ms ✅ | 500ms ✅ | 800ms ✅ |
| Supercluster + canvas | 100ms ✅ | 200ms ✅ | 350ms ✅ | 500ms ✅ |

**Target Performance Goals:**
- Initial load: &lt;500ms (perceived)
- Pan/zoom: &lt;200ms response
- Marker click: &lt;100ms
- Mobile: 2x desktop times acceptable

## UX Patterns

### Cluster Interaction Patterns

1. **Click to Expand** (Recommended)
   - Click cluster → zoom to expansion zoom level
   - Shows "spider" view of underlying points

2. **Click to List**
   - Click cluster → show sidebar with all items
   - Good for dense areas (downtown cores)

3. **Hover Preview**
   - Hover cluster → show count + top 3 items
   - Good for discovery UX

### Loading States

```tsx
{isLoading && (
  <div className="absolute inset-0 bg-leather-900/50 backdrop-blur-sm z-[1000] flex items-center justify-center">
    <div className="text-sand-100">
      Loading {loadedCount} of {totalCount} locations...
    </div>
  </div>
)}
```

### Empty States

```tsx
{!isLoading && clusters.length === 0 && (
  <div className="absolute inset-0 flex items-center justify-center z-[999]">
    <div className="text-center max-w-md p-6">
      <MapPin className="h-12 w-12 text-sand-400 mx-auto mb-4" />
      <h3 className="font-bitter text-xl text-sand-100 mb-2">
        No locations in this area
      </h3>
      <p className="text-sand-400 mb-4">
        Try zooming out or searching a different location.
      </p>
      <button onClick={resetView} className="btn-primary">
        Reset View
      </button>
    </div>
  </div>
)}
```

## Common Pitfalls

### ❌ Anti-patterns to Avoid

1. **Loading all data upfront**
   ```tsx
   // BAD: Fetches 10k records on mount
   const { data } = useQuery(["all-places"], fetchAllPlaces);
   ```

2. **Re-rendering on every map move**
   ```tsx
   // BAD: Updates state on every pixel
   map.on("move", () => setBounds(map.getBounds()));
   ```

3. **Complex marker components**
   ```tsx
   // BAD: React component per marker
   <Marker icon={<ComplexSVGComponent />} />
   ```

4. **No zoom-level adaptation**
   ```tsx
   // BAD: Same clustering at all zoom levels
   const clusterOptions = { radius: 80, maxZoom: 20 };
   ```

### ✅ Best Practices

1. **Viewport-based loading with debouncing**
2. **Simple marker icons (divIcon with inline styles)**
3. **Progressive disclosure (adapt to zoom level)**
4. **Canvas rendering for large datasets**
5. **Proper React Query cache configuration**

## Real-World Examples

### Zillow Pattern
- **Low zoom**: Neighborhood price clusters
- **Medium zoom**: Individual properties with price
- **High zoom**: Full property cards
- **Click**: Expand cluster or open details

### Airbnb Pattern
- **Server-side**: Pre-cluster at 10 zoom levels
- **Client-side**: Viewport API with 300ms debounce
- **Rendering**: Canvas for price labels
- **Interaction**: Hover for preview, click for details

### OpenStreetMap Pattern
- **Tile-based**: Pre-rendered raster tiles
- **Vector tiles**: For 100k+ POIs
- **Simplification**: Reduce detail at low zoom
- **Caching**: Aggressive CDN + browser cache

## Tech Stack Compatibility

### Frameworks
- ✅ Next.js 13+ (App Router + Server Components)
- ✅ Next.js Pages Router
- ✅ Vite + React
- ✅ Remix
- ✅ Astro (with client islands)

### Databases
- ✅ **Supabase (PostGIS)** - Recommended, built-in spatial indexing
- ✅ PostgreSQL + PostGIS
- ⚠️ MongoDB (geospatial queries slower than PostGIS)
- ⚠️ Firebase (limited spatial query support)

### Map Libraries
- ✅ **Leaflet.js** - Best for static tiles + markers
- ✅ Mapbox GL JS - Better for vector tiles
- ✅ Maplibre GL JS - Open-source Mapbox alternative
- ❌ Google Maps API - Expensive, less flexible

## Migration Checklist

When optimizing an existing slow map:

- [ ] Measure current performance (Chrome DevTools Performance tab)
- [ ] Count total markers/points in dataset
- [ ] Check if spatial index exists on database (`EXPLAIN ANALYZE`)
- [ ] Install clustering library (`npm install use-supercluster`)
- [ ] Implement viewport-based loading
- [ ] Add canvas renderer option
- [ ] Test on mobile device (4G throttling)
- [ ] Add loading states
- [ ] Implement progressive disclosure
- [ ] Set up performance monitoring
- [ ] Document zoom-level behaviors

## Dependencies

```json
{
  "dependencies": {
    "leaflet": "^1.9.4",
    "react-leaflet": "^4.2.1",
    "supercluster": "^8.0.1",
    "use-supercluster": "^1.2.0",
    "@tanstack/react-query": "^5.0.0",
    "use-debounce": "^10.0.0"
  }
}
```

## References

### Research Papers
- [Performance Testing on Marker Clustering (2019)](https://www.researchgate.net/publication/334853181)
- [Spatial Indexing Performance in PostgreSQL](https://postgis.net/workshops/postgis-intro/indexing.html)

### Technical Guides
- [Leaflet Performance Guide (Andrej Gajdos)](https://andrejgajdos.com/leaflet-developer-guide-to-high-performance-map-visualizations-in-react/)
- [PostGIS Spatial Queries | Supabase Docs](https://supabase.com/docs/guides/database/extensions/postgis)
- [Supercluster GitHub](https://github.com/mapbox/supercluster)
- [use-supercluster React Hook](https://github.com/leighhalliday/use-supercluster)

### UX Research
- [Map-Based UX in Real Estate (RAW Studio)](https://raw.studio/blog/using-maps-as-the-core-ux-in-real-estate-platforms/)
- [Progressive Disclosure in Maps (UX Matters)](https://www.uxmatters.com/mt/archives/2020/05/designing-for-progressive-disclosure.php)

## Version History

- 2026-01-09: Initial skill creation based on sobriety.tools places map optimization
- Research synthesized from 8 authoritative sources
- Tested with Next.js 15, Leaflet 1.9.4, Supabase PostGIS

---

**Skill Author**: Claude Code (Sonnet 4.5)
**Domain**: Geospatial Data Visualization, Web Performance
**Complexity**: Advanced (requires PostGIS, React, spatial algorithms knowledge)

© curiositech · MIT · curiositech/some_claude_skills

Similar skills

All skills for Frontend and UI →
geospatial-and-cartographic-visualization official OpenAI The geospatial-and-cartographic-visualization skill helps plan maps by choosing projections, basemaps, visualization types, and implementation tools. Use it for thematic maps, routes, and spatial datasets. CX Codex GP ChatGPT +1 13installs data-visualization official OpenAI data-visualization — a skill for Codex and ChatGPT that acts as an orchestrator for web visualization work: it classifies the task, picks the smallest set of specialist skills, and routes before any code gets written. CX Codex GP ChatGPT +1 26installs mapbox-data-visualization-patterns mapbox mapbox-data-visualization-patterns is a Claude Code skill with patterns for choropleths, heatmaps, and 3D styling when visualizing statistics or point density. CX Codex +1 2,200installs mapbox-style-patterns mapbox mapbox-style-patterns is a skill for Claude Code and Codex with ready-made Mapbox layers and styles for common maps. It covers POI, real estate, navigation, and delivery maps. CX Codex +1 2,400installs code-map-visualization pproenca code-map-visualization tells the agent how to draw a codebase map that is already projected: which attribute goes on position, size or colour, and how to stay inside a 16 ms frame. CX Codex +1 145installs zero-build-frontend jamditis zero-build-frontend — a skill for building frontend code that runs directly in the browser without a build step. Covers static sites, browser extensions, maps, and lightweight data-backed interfaces. CX Codex +1 198installs

From the same set180

The whole set →
design-system-creator The design-system-creator skill builds design systems with tokens, CSS structure, component docs, and style guides. Use it when a project needs a shared UI foundation. CX Codex +1 250installs fullstack-debugger fullstack-debugger troubleshoots Next.js 15, Cloudflare Workers, and Supabase apps layer by layer. Fixes auth errors, broken RLS policies, CORS, and build failures. CX Codex +1 244installs security-auditor security-auditor runs dependency checks, finds hardcoded secrets, and flags injection or XSS risks in source code. Useful before shipping or when reviewing a pull request. CX Codex +1 243installs native-app-designer native-app-designer — a skill for iOS, Mac and web app design that skips the generic AI look. It steers the agent toward spring physics, motion timing and details that make an interface feel human. CX Codex +1 241installs api-architect api-architect is a Claude Code skill that guides REST, GraphQL, and gRPC API design, from contracts and schemas to documentation and specification checks. CX Codex +1 235installs vaporwave-glassomorphic-ui-designer vaporwave-glassomorphic-ui-designer — a skill for designing photo and memory apps with vaporwave and glassmorphic looks. Use it when you need SwiftUI interfaces with frosted glass, neon pastels, and a retro-futuristic feel. CX Codex +1 234installs diagramming-expert The diagramming-expert skill turns architectures, processes, and relationships into text diagrams. Use it when a system is easier to explain with boxes, lines, and arrows. CX Codex +1 232installs design-critic design-critic evaluates UI and component code across 6 weighted aesthetic dimensions. Generates structured review scores and actionable remix suggestions. CX Codex +1 230installs

Project sponsors

Companies that keep this analytics open