Framework
1.13.0 GitHub️ 2.5k

TopoJSON

TopoJSON is an extension of GeoJSON, a format for encoding geometry and geographic data structures, that further encodes topology. The TopoJSON client library allows you to transform compact TopoJSON files to GeoJSON and display a map with — for instance — Leaflet, D3, or Observable Plot. The TopoJSON client library is available in Markdown as topojson, but you can also import it like so:

import * as topojson from "npm:topojson-client";

To demonstrate, let’s load a file that describes the counties, states and general outline of the United States, already projected using Albers’ equal area-conic projection to a frame of 975×610 pixels:

const us = FileAttachment("counties-albers-10m.json").json();
us

We can then create a GeoJSON object for each feature we want to display. First, the general outline of the nation:

const nation = topojson.feature(us, us.objects.nation);
nation

The counties mesh, which includes each of the delimitations once (instead of once per county). This avoids an additional stroke on the perimeter of the map, which would otherwise mask intricate features such as islands and inlets.

const countiesmesh = topojson.mesh(us, us.objects.counties);
countiesmesh

The statemesh likewise contains the internal borders between states, i.e., everything but the coastlines and country borders.

const statemesh = topojson.mesh(us, us.objects.states, (a, b) => a !== b)
statemesh

Putting it together as a map using Observable Plot:

Plot.plot({
  projection: "identity",
  width: 975,
  height: 610,
  marks: [
    Plot.geo(countiesmesh, {strokeOpacity: 0.5}),
    Plot.geo(statemesh, {strokeWidth: 0.75}),
    Plot.geo(nation, {strokeWidth: 1.5})
  ]
})

If you need to manipulate topologies, for example to simplify the shapes on-the-fly, you may need to import the TopoJSON server and TopoJSON simplify libraries, too.

import {topology} from "npm:topojson-server";
import {presimplify, simplify} from "npm:topojson-simplify";

For more details, please refer to the TopoJSON documentation.