---
title: "Geo Map: S2 Cells"
description: "S2 cells in the browser: the cell holding a GPS position at any of 31 levels, hexadecimal tokens and exact 64-bit ids as BigInt, centers and corners, edge neighbors, parents and children - drawn on the Geo Map."
slug: "geo-s2"
---

import { DocPage, PageHeader, SourceFiles, SourceNote, DocText, DocLink, H2 } from "../../lib/components/index";

<DocPage meta={meta}>

<PageHeader slug="geo-s2" title="S2 Cells" component="geo-map">
  S2 divides the sphere into a cube's six faces and each face, again and again, into four - 31 levels, from a face to about a square centimetre. A cell is one 64-bit number whose leading bits are its ancestors, ordered along a Hilbert curve, so nearby places share prefixes and a range of ids is a region. <code>df$.shadcn.geo</code> has the S2 operations an application needs, synchronous and without an engine: <code>s2Cell(position, level)</code>, <code>s2Center</code>, <code>s2Vertices</code>, <code>s2Polygon</code>, <code>s2Neighbors</code>, <code>s2Parent</code>, <code>s2Children</code>, <code>s2Level</code>, <code>s2Id</code> and <code>s2Token</code>.
</PageHeader>

<H2 id="cell">A position's cell</H2>

<DocText><code>s2Cell([lon, lat], level)</code> returns <code>\{ id, token, level \}</code>: the id as a <code>BigInt</code> (64 bits do not fit a JavaScript number), the token as the canonical hex string with trailing zeros dropped. A string argument is always a token - pass a decimal id as <code>BigInt(decimalString)</code>. On the map, cells are a layer: their tokens in <code>cells</code>, drawn with great-circle edges and pickable like regions (<code>s2:&lt;token&gt;</code>).</DocText>

```html example label="The cell of a GPS position, its neighbors and its parent" schema="none" hint="Move the level: the cell holding the position shrinks four times per level; the four edge neighbors are drawn around it, the parent's center is the square marker. Click a cell to pick it." previewStyle="align-items:stretch;"
<div class="grid gap-3">
  <div class="flex flex-wrap items-end gap-3">
    <div class="grid gap-1">
      <label class="label" for="s2-pos">Position - longitude, latitude</label>
      <input class="input" id="s2-pos" value="11.582, 48.1351" spellcheck="false" />
    </div>
    <div class="grid gap-1">
      <label class="label" for="s2-level">Level <output id="s2-level-out">8</output></label>
      <input class="slider" type="range" id="s2-level" min="2" max="14" value="8" />
    </div>
  </div>
  <pre class="text-xs m-0" id="s2-info"></pre>
  <div
    class="geo-map"
    id="cells"
    aria-label="S2 cells"
    data-projection="mercator"
    data-center="11.6,48.1"
    data-zoom="40"
    data-palette="mono"
    data-graticule="false"
  ></div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', async () => {
    const geo = df$.shadcn.geo;
    const map = df$('#cells').get(0);
    await map.api.settled();
    const draw = (move) => {
      const level = Number(df$('#s2-level').val());
      df$('#s2-level-out').text(String(level));
      try {
        const position = df$('#s2-pos').val().split(',').map(Number);
        const cell = geo.s2Cell(position, level);
        const parent = geo.s2Parent(cell.token);
        df$('#s2-info').text(
          'token ' +
            cell.token +
            '   id ' +
            cell.id +
            '\ncenter ' +
            geo
              .s2Center(cell.token)
              .map((n) => n.toFixed(5))
              .join(', ') +
            '   parent ' +
            parent +
            '   children ' +
            geo.s2Children(cell.token).join(' '),
        );
        df$.shadcn.geoMap.setLayers(map, {
          cells: [cell.token, ...geo.s2Neighbors(cell.token)],
          markers: [
            { id: 'gps', label: 'GPS', position, shape: 'pin' },
            { id: 'parent', position: { s2: parent }, shape: 'square', color: 'var(--chart-4)' },
          ],
          styles: {
            ['s2:' + cell.token]: { fill: 'color-mix(in oklab, var(--chart-2) 55%, transparent)', strokeWidth: 2 },
          },
        });
        if (move) df$.shadcn.geoMap.setView(map, geo.s2Center(cell.token), Math.min(1024, 2 ** level / 3), false);
      } catch (err) {
        df$('#s2-info').text(err.message);
      }
    };
    df$('#s2-level').on('input', () => draw(true));
    df$('#s2-pos').on('change', () => draw(true));
    draw(true);
  });
</script>
```

<H2 id="hierarchy">The hierarchy</H2>

<DocText>Every cell has exactly four children and one parent; a cell's id contains its parent's as a prefix, which is why <code>s2Parent</code> and <code>s2Children</code> are bit operations. The six faces are level 0 - here they are, colored, with their children at level 1.</DocText>

```html example label="The cube faces and their children" schema="none" previewStyle="align-items:stretch;"
<div
  class="geo-map"
  id="faces"
  aria-label="The six S2 faces"
  data-projection="orthographic"
  data-center="20,30"
  data-palette="mono"
></div>
<script>
  document.addEventListener('DOMContentLoaded', async () => {
    const geo = df$.shadcn.geo;
    const map = df$('#faces').get(0);
    await map.api.settled();
    const faces = ['1', '3', '5', '7', '9', 'b'];
    const children = faces.flatMap((f) => geo.s2Children(f));
    const styles = {};
    faces.forEach((f, i) => {
      for (const c of geo.s2Children(f))
        styles['s2:' + c] = { fill: 'color-mix(in oklab, var(--chart-' + ((i % 5) + 1) + ') 45%, transparent)' };
    });
    df$.shadcn.geoMap.setLayers(map, { cells: children, styles });
  });
</script>
```

<H2 id="drill-down">Drill down the hierarchy</H2>

<DocText>A cell can be the map's focus, like a region: <code>data-focus="s2:&lt;token&gt;"</code> - or a double click on any drawn cell - frames the cell and draws its four children in place of the layer's cells; the countries stay as they are. Double click a child to go one level deeper; <code>up</code>, Escape or <code>df$.shadcn.geoMap.up(el)</code> step back to the parent, and from a face to the cells the page set. Each step is a <code>geo-map-focus</code> event, and the <code>level</code> readout names the level drawn. The camera stops at 1024x: on this map that frames a cell down to level 8, and from level 9 on each step halves the children - about 20 px across at level 12.</DocText>

```html example label="From a cube face down through the levels" schema="none" hint="Double click a cell to drill into it, or press Into Munich's cell to go down one level toward Munich's GPS position. Up steps out; World goes back to the six faces." previewStyle="align-items:stretch;"
<div class="grid gap-3">
  <div class="flex flex-wrap items-center gap-2">
    <button class="btn" data-size="sm" type="button" id="s2-down">Into Munich's cell</button>
    <button class="btn" data-variant="outline" data-size="sm" type="button" data-geo-for="s2-drill" data-geo-action="up"
      >Up</button
    >
    <button
      class="btn"
      data-variant="ghost"
      data-size="sm"
      type="button"
      data-geo-for="s2-drill"
      data-geo-action="reset"
      >World</button
    >
    <span class="text-sm"
      >Framed: <output data-geo-for="s2-drill" data-geo-output="focus"></output> - drawn:
      <output data-geo-for="s2-drill" data-geo-output="level"></output
    ></span>
  </div>
  <div
    class="geo-map"
    id="s2-drill"
    aria-label="The S2 hierarchy"
    data-projection="equalArea"
    data-center="11.6,48.1"
    data-palette="mono"
    data-highlight="outline"
  >
    <script type="application/json" class="geo-map-layers">
      {
        "cells": ["1", "3", "5", "7", "9", "b"],
        "markers": [{ "id": "muc", "label": "Munich", "position": [11.582, 48.1351], "shape": "pin" }]
      }
    </script>
  </div>
</div>
<script>
  document.addEventListener('DOMContentLoaded', () => {
    const geo = df$.shadcn.geo;
    const map = df$('#s2-drill').get(0);
    df$('#s2-down').on('click', () => {
      const focus = map.dataset.focus ?? '';
      const level = focus.startsWith('s2:') ? geo.s2Level(focus.slice(3)) + 1 : 0;
      df$.shadcn.geoMap.focus(map, 's2:' + geo.s2Cell([11.582, 48.1351], Math.min(30, level)).token);
    });
  });
</script>
```

<H2 id="morton-vs-s2">S2 and Morton are different curves</H2>

<DocText>S2 orders cells along a Hilbert curve on the cube's faces - neighbors along the curve are always neighbors on the ground. The <DocLink href="geo-routing.html">routing</DocLink> page's Morton index orders a plain longitude / latitude grid along a Z curve instead: simpler, and enough to cut a rectangle query down to a few key ranges. Neither is a road network, and S2 cells are spherical, not ellipsoidal: they are equal in neither area nor shape, only within a factor of about two.</DocText>

<SourceFiles component="geo-map" section="css">
  <SourceNote for="css">The library lives in the Geo Map component - the stylesheet is the map's.</SourceNote>
</SourceFiles>

<SourceFiles component="geo-map" section="js" jsTitle="JS" />

</DocPage>
