Maplace.js

Locations: markers, circles, polylines, polygons and multipolygons

Markdown

A location is one item of your data: a marker, a circle, a polyline, a polygon or a multipolygon. Locations are a union on type; one without a type is a marker. Ids are yours (Maplace.js never generates them) and must be unique; coordinates are lat and lng, in degrees. Optional fields accept an explicit undefined, so mapping your data across stays simple. Any other field throws invalid-input: your own fields go in data. The full rules are in RFC §3 Shape.

import type { Location } from "@maplacejs/maplace";
import { createGoogleMap } from "@maplacejs/maplace/google";

/** Your own code, writing an edited location back to your server. */
declare function save(location: Location): Promise<void>;

const locations: Location[] = [
  {
    id: "park",
    type: "polygon",
    title: "Hyde Park",
    editable: true,
    path: [
      { lat: 51.512, lng: -0.175 },
      { lat: 51.513, lng: -0.16 },
      { lat: 51.503, lng: -0.155 },
    ],
  },
];
const maplace = createGoogleMap("#polygon-vanilla-map", { locations });
maplace.on("locationChange", ({ location }) => save(location));

On a page with the element, a <maplace-location> sets the same fields from its attributes; the last column says which.

Every location

Field Type What In HTML
id string Stable identity: updates, selection and routes refer to it. Required, unique location-id
type "marker" | "circle" | "polyline" | "polygon" | "multipolygon" Which shape it is; a marker when left out type
title string Plain text: the list label, the accessible name on the map and its popup’s heading title
content Content The popup’s content a <template> child
html string Untrusted HTML for the popup instead of content, rendered only through the store’s sanitize
group string | string[] Grouping key for list headings and setFilter: one per location, a name or (1.2) a path of up to 3 names, outermost first, such as ["Europe", "Italy"], which the list nests (Subgroups) group: a name, or a path as JSON when it starts with [ (group='["Europe","Italy"]'), so a name starting with [ is written in locations instead
tags string[] What setFilter also filters on, as many as it has; never a heading tags, split on spaces
searchText string What a setFilter query also looks in, beside the name and group: an address, say; data isn’t searched search-text
zoom number The zoom selecting it shows it at, centred where its popup points; a select()’s own zoom wins zoom
visible boolean false keeps it in the data but not drawn, listed or selected. Default true
listed boolean false leaves it out of every list view; the map still draws it and it is selected there. Default true listed
editable boolean Lets the user drag a marker or reshape a shape; needs the edit capability; not with a polyline’s curve or geodesic, nor on a multipolygon editable
data your type Your own fields, handed back to content, icon and render functions

Markers

Field Type What In HTML
lat, lng number Where it is: lat from -90 to 90, lng from -180 to 180 lat, lng
icon Icon A custom marker in place of the provider’s own icon (a URL), or a <template data-icon> child
weight number Its weight on a heatmap, against the other markers’ (1.2); 1 when unset

Circles

Field Type What In HTML
center { lat, lng } Its centre lat, lng
radius number Its radius, in metres radius
style ShapeStyle How it is drawn, over the store’s style shape-style (JSON)
selectedStyle ShapeStyle Drawn over style while selected selected-style (JSON)
hoveredStyle ShapeStyle Drawn over style while hovered and not selected hovered-style (JSON)
active boolean Marks it as the page’s current one: drawn in the hovered look while neither hovered nor selected, not lifted above other shapes active
activeStyle ShapeStyle Drawn over style while active, neither hovered nor selected active-style (JSON)

Polylines

Field Type What In HTML
path { lat, lng }[] Its points, at least 2
curve number How far each segment bows from a straight line, for the look, -1 to 1: at 1, its middle sits half its length (in degrees) to the left going from the first point to the last; to the right when negative. Default 0, straight; not with geodesic or editable
geodesic boolean Draws each segment along its great circle, the shortest way on the earth: a flight’s path, a point a degree of arc. Default false; not with curve or editable
progress number How much of the line is travelled, 0 to 1 along it as drawn: that part is drawn in the travelled look, the rest as the line, and a click or hover on either is the line’s. Unset, the line is drawn whole; not with editable
travelledStyle LineStyle The travelled part’s style, over its look: the line’s own in its state, at 40% of its opacity
style LineStyle How it is drawn: a stroke, no fill shape-style (JSON)
selectedStyle LineStyle Drawn over style while selected selected-style (JSON)
hoveredStyle LineStyle Drawn over style while hovered and not selected hovered-style (JSON)
active boolean Marks it as the page’s current one: drawn in the hovered look while neither hovered nor selected, not lifted above other shapes active
activeStyle LineStyle Drawn over style while active, neither hovered nor selected active-style (JSON)

A polyline or a polygon is one location with a path; in HTML, give it in the map’s inline JSON script (the element’s data).

Curves and great circles

Two ways to draw a line other than straight. Either is drawn the same on every map, crosses ±180 the short way, and keeps its popup and fit-all on the drawn line; neither is editable, as an edit would write the drawn points back as the path.

  • geodesic: true follows the earth: on a flat map, a long line bows towards the pole, as a flight does.
  • curve bows each segment for the look, with no geographic meaning: a lane, a link between two places. Trade lanes bows its lanes this way:
const lane = { id: "rotterdam-new-york", type: "polyline", curve: -0.2,
  path: [{ lat: 51.9244, lng: 4.4777 }, { lat: 40.7128, lng: -74.006 }] };

London’s flights, each on its great circle, two dashed as scheduled and one in the air, travelled as far as a slider says:

import { type LatLng, type Location, type PolylineLocation, pointAlong } from "@maplacejs/maplace";
import { createGoogleMap } from "@maplacejs/maplace/google";

// London's flights out, each along its great circle, the shortest way on the earth, the ones
// still scheduled dashed. The flight to New York is in the air: drawn active, travelled as far as
// the slider says, with its plane there.
const london: LatLng = { lat: 51.5074, lng: -0.1278 };
const newYork = { id: "new-york", name: "New York", lat: 40.7128, lng: -74.006 };
const cities = [
  newYork,
  { id: "sao-paulo", name: "São Paulo", lat: -23.5505, lng: -46.6333 },
  { id: "cape-town", name: "Cape Town", lat: -33.9249, lng: 18.4241 },
  { id: "dubai", name: "Dubai", lat: 25.2048, lng: 55.2708 },
  { id: "mumbai", name: "Mumbai", lat: 19.076, lng: 72.8777 },
  { id: "singapore", name: "Singapore", lat: 1.3521, lng: 103.8198 },
  { id: "tokyo", name: "Tokyo", lat: 35.6895, lng: 139.6917 },
  { id: "sydney", name: "Sydney", lat: -33.8688, lng: 151.2093 },
];
const scheduled = new Set(["cape-town", "sydney"]);
/** A plane, nose up, as an image. */
const plane =
  "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' viewBox='0 0 24 24'%3E%3Cpath fill='%231d4ed8' stroke='white' d='M12 2l1.5 7 8.5 4v2l-8.5-2.5-.5 5.5 2.5 2v1.5l-3.5-1-3.5 1V20l2.5-2-.5-5.5L2 15v-2l8.5-4z'/%3E%3C/svg%3E";

function flightTo({ id, name, lat, lng }: typeof newYork): PolylineLocation {
  return {
    id: `london-${id}`,
    type: "polyline",
    title: `London → ${name}`,
    path: [london, { lat, lng }],
    geodesic: true,
    style: scheduled.has(id) ? { stroke: "#2563eb", strokeDash: "dashed" } : { stroke: "#2563eb" },
  };
}

// Made once, so a move of the slider changes only the flight in the air and its plane.
const places: Location[] = [
  // The cities and the plane on the map only; the list holds the flights.
  { id: "london", ...london, title: "London", listed: false },
  ...cities.map(({ id, name, lat, lng }) => ({ id, lat, lng, title: name, listed: false })),
];
const toNewYork = flightTo(newYork);
const otherFlights = cities.slice(1).map(flightTo);

/** The map's locations, the flight to New York `flown` (0 to 1) of the way there. */
function flightsWith(flown: number): Location[] {
  const inTheAir: PolylineLocation = { ...toNewYork, active: true, progress: flown };
  const at = pointAlong(inTheAir, flown);
  const planeThere = {
    id: "plane",
    ...at,
    title: "The plane to New York",
    icon: plane,
    listed: false,
  };
  return [...places, inTheAir, ...otherFlights, planeThere];
}

const flown = document.getElementById("flights-vanilla-flown-input") as HTMLInputElement;
const maplace = createGoogleMap("#flights-vanilla-map", {
  locations: flightsWith(flown.valueAsNumber),
  list: { container: "#flights-vanilla-list", heading: "Flights from London" },
});
flown.addEventListener("input", () => maplace.setLocations(flightsWith(flown.valueAsNumber)));

Polygons

Field Type What In HTML
path { lat, lng }[] Its outer ring, at least 3 points
holes { lat, lng }[][] Inner rings, at least 3 points each
style ShapeStyle How it is drawn, over the store’s style shape-style (JSON)
selectedStyle ShapeStyle Drawn over style while selected selected-style (JSON)
hoveredStyle ShapeStyle Drawn over style while hovered and not selected hovered-style (JSON)
active boolean Marks it as the page’s current one: drawn in the hovered look while neither hovered nor selected, not lifted above other shapes active
activeStyle ShapeStyle Drawn over style while active, neither hovered nor selected active-style (JSON)

Multipolygons

Several polygons that are one location, such as a country with its islands: drawn, hovered and selected as one shape, with one entry in a list. It is shown at its largest polygon: its popup points at the centre of that polygon’s bounds, and selecting it fits that polygon, so selecting France shows France rather than the ocean between it and French Guiana; fitting every location, and “This area”, count all its polygons. A multipolygon isn’t editable (editable: true is invalid-input): give the polygon to reshape a location of its own. It needs the multipolygon capability, which Google’s and MapLibre’s adapters have, from 1.2; an adapter written for 1.0 lacks it, so the store refuses a multipolygon there. A GeoJSON MultiPolygon becomes one (From GeoJSON).

Field Type What In HTML
polygons { path, holes? }[] Its polygons, at least one: each a polygon’s outer ring (path, at least 3 points) and its inner rings (holes, at least 3 points each)
style ShapeStyle How it is drawn, over the store’s style shape-style (JSON)
selectedStyle ShapeStyle Drawn over style while selected selected-style (JSON)
hoveredStyle ShapeStyle Drawn over style while hovered and not selected hovered-style (JSON)
active boolean Marks it as the page’s current one: drawn in the hovered look while neither hovered nor selected, not lifted above other shapes active
activeStyle ShapeStyle Drawn over style while active, neither hovered nor selected active-style (JSON)

Styles

A style says how a shape or a route line is drawn. Colours are CSS colours and widths are pixels. A LineStyle (polylines, routes) has the stroke fields and the dash; a ShapeStyle (circles, polygons) has the stroke fields, its outline always solid, and the fill.

Field Type What
stroke string The line’s colour
strokeOpacity number The line’s opacity, 0 to 1
strokeWidth number The line’s width
strokeDash "solid" | "dashed" | "dotted" How the line runs: unbroken (the default), in dashes 2 widths long with gaps as long, or in dots a width across every 2 widths; on a polyline or a route only, not in the store’s default styles
fill string The fill’s colour; not on a polyline
fillOpacity number The fill’s opacity, 0 to 1; not on a polyline

A shape in a state is drawn as Maplace.js’s own look for that state, then its style, then its state style (selectedStyle, hoveredStyle or activeStyle), each the location’s over the store’s (store options). Selected wins over hovered, and hovered over active, which a shape is while its active is true and has the hovered look. The state style comes last, so a store-wide selectedStyle shows on every shape whatever its own colours.

A point along a line

pointAlong(line, fraction) gives the point fraction (0 to 1) of the way along a polyline location as it is drawn (bowed by curve or along great circles when it is geodesic), or along a route result’s path: for a marker of your own that moves along a line. Halfway is where the line’s popup points. A fraction outside 0 to 1, or anything but a polyline location or a route result, is invalid-input. A line’s path is measured once, as the store draws it once: give a new array when its points change, as with any location.

Content

A popup’s content is one of:

  • a string, always rendered as text, never parsed as HTML;
  • a DOM node;
  • a function of the location returning a node.

For rich content, pass a node or a function. html takes a string of HTML instead, and only with the store’s sanitize option, which must return safe HTML; giving both content and html is invalid-input. A location without either opens no popup: a click selects it.

Icons

A marker’s icon is one of:

  • an image URL, shown at the image’s own size, above the point and centred on it;
  • a DOM node;
  • a function of the location and its state ({ selected, hovered }) returning a node, run again only for markers whose state changed.

For another size, give a sized <img>. For another anchor, move the node with CSS: display: block; transform: translateY(50%) puts its centre on the point. A popup still opens from the node’s place before the move.

A DOM marker carries data-selected and data-hovered while in that state, so [data-selected] in CSS styles it. An icon or content function that throws, or returns something other than a node, is an invalid-input error event naming the location and the field: the map stays ready and draws the default marker, or opens no popup (RFC §3 Errors).

From GeoJSON

locationsFromGeoJSON turns a GeoJSON FeatureCollection into locations, ready for setLocations. It is in the core entry, so it needs no provider; on the CDN scripts it is Maplace.locationsFromGeoJSON.

// Locations from a GeoJSON file: its Points, LineStrings, Polygons and MultiPolygons, ids its own.
import { locationsFromGeoJSON, type Maplace } from "@maplacejs/maplace";

declare const maplace: Maplace; // your store, e.g. from createGoogleMap or createMapLibreMap

const response = await fetch("/places.geojson");
maplace.setLocations(locationsFromGeoJSON(await response.json()));

Each feature becomes one location:

  • a Point becomes a marker, a LineString a polyline, a Polygon a polygon (its first ring is the path and the others its holes), and a MultiPolygon one multipolygon, each of its polygons read as a Polygon’s rings, even when it has only one;
  • positions are GeoJSON’s [lng, lat], turned into { lat, lng }; an altitude is dropped, and so is a ring’s closing point (a last point equal to the first);
  • id is the feature’s id, a number becoming its string;
  • title and group are the properties’ own: strings (group also a list of names, a path), or null or absent for none;
  • tags are the properties’ own when they are a list; anything else called tags, such as an OpenStreetMap export’s object, stays in data alone;
  • data is the properties whole, title, group and tags included; null or no properties means no data.

A feature without an id, or with another geometry (MultiPoint, MultiLineString, a GeometryCollection, none), or a title, a group or a list of tags that isn’t text, is invalid-input naming it, such as features[2].geometry.type. The values are checked as any location’s are, when the store takes them. Map the features across first when the file doesn’t fit, on the JSON as loaded (with your own types, cast properties to them):

  • ids kept in a property: locationsFromGeoJSON({ ...collection, features: collection.features.map((feature) => ({ ...feature, id: feature.properties?.code })) });
  • no ids at all, as files from many tools have: the same call with map((feature, index) => ({ ...feature, id: String(index) })); such ids stay the same only while the file keeps its order;
  • other geometries: features: collection.features.filter((feature) => ["Point", "LineString", "Polygon", "MultiPolygon"].includes(feature.geometry?.type ?? "")) in the same call keeps the ones it reads, or split them yourself, with ids of your own;
  • typed properties: locationsFromGeoJSON<Shop>(json) types each location’s data, as createMaplace<Shop>() does.

On <maplace-map>, set the locations property to the result. With React, compute it once, at module scope or in useMemo: <MaplaceProvider locations> applies every new array it is given.

Addresses to coordinates

Maplace.js itself takes coordinates, never addresses, at run time. A page with addresses geocodes them once, before it ships, and keeps the result if its geocoder allows it: no provider quota, no key in your page, nothing sent about your readers. For an address a visitor types, see A visitor’s address.

May you keep the results?

Read on 2026-10-27:

Geocoder Keep the results? Source
Google Geocoding API No: cached up to 30 days, and shown only on a Google map Service terms, policies
Mapbox Only through permanent geocoding (permanent=true), billed at a higher rate Temporary vs permanent
OpenCage Yes, under the data’s licences (OpenStreetMap’s ODbL) Terms
LocationIQ Paid plans, while you are a customer; the free plan caches up to 48 hours Pricing
MapTiler Yes for most uses, by their search FAQ; the free plan is non-commercial Search FAQ, pricing
Public Nominatim Not for bulk: one request a second at most, and no systematic geocoding Usage policy
Self-hosted Nominatim or Photon Yes: the data is OpenStreetMap’s, under the ODbL OpenStreetMap copyright

Terms change: read your geocoder’s before you run it.

Results from OpenStreetMap data (OpenCage, Nominatim, Photon, and any other geocoder built on it) need “© OpenStreetMap contributors” on the page that shows them (OpenStreetMap copyright).

The script

Save it as geocode.mts and run GEOCODER_KEY=your-key node geocode.mts places.json (Node 22.18 or later runs it as it is). It reads places such as [{ "id": "rome", "title": "Rome office", "address": "Via del Corso 1, Rome" }] and writes each back with lat and lng, its address in data; a run stopped partway keeps what it placed, and the next asks only for what is left.

// Addresses to coordinates, once, before your page ships: each place in places.json without
// coordinates gets them from the geocoder, its address kept in `data`. The key comes from the
// environment, never as an argument: GEOCODER_KEY=your-key node geocode.mts places.json
import { readFile, rename, writeFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";

interface Place {
  readonly id: string;
  readonly address?: string;
  readonly lat?: number;
  readonly data?: object;
}

/** OpenCage; another geocoder is its URL and where its answer puts the point. */
const geocoder = {
  url: (address: string, key: string) =>
    `https://api.opencagedata.com/geocode/v1/json?limit=1&no_annotations=1&key=${encodeURIComponent(key)}&q=${encodeURIComponent(address)}`,
  pointIn: (answer: { results: { geometry: { lat: number; lng: number } }[] }) =>
    answer.results[0]?.geometry,
};

const key = process.env.GEOCODER_KEY;
if (!key) throw new Error("Set GEOCODER_KEY to your geocoder's key");
const file = process.argv[2] ?? "places.json";
const places: Place[] = JSON.parse(await readFile(file, "utf8"));
for (const [index, { address, ...place }] of places.entries()) {
  if (place.lat !== undefined || !address?.trim()) continue;
  const response = await fetch(geocoder.url(address, key));
  if (!response.ok) {
    throw new Error(
      `${response.status} for "${address}": check the address, GEOCODER_KEY and your quota`,
    );
  }
  const point = geocoder.pointIn(await response.json());
  if (point) {
    places[index] = { ...place, ...point, data: { ...place.data, address } };
    // Saved at once, so a run stopped partway keeps what it placed; written aside, then moved
    // over the original, so a failed write never truncates it.
    await writeFile(`${file}.tmp`, `${JSON.stringify(places, null, 2)}\n`);
    await rename(`${file}.tmp`, file);
  } else {
    console.warn(`No match: ${address}`);
  }
  await sleep(1000); // one request a second: OpenCage's free rate
}

A place still holding an address (printed as No match, or blank), or with neither an address nor coordinates, isn’t a location yet: correct its address and run the script again, or drop it. Then load the file as your locations: the element’s inline JSON, setLocations, or <MaplaceProvider locations>.

Another geocoder

Swap geocoder for another one whose terms let you keep the results: its request, and where its answer puts the point.

Geocoder url(address, key) pointIn(answer)
Self-hosted Nominatim `https://your-nominatim/search?format=jsonv2&limit=1&q=${encodeURIComponent(address)}` answer[0] && { lat: Number(answer[0].lat), lng: Number(answer[0].lon) }
Self-hosted Photon `https://your-photon/api?limit=1&q=${encodeURIComponent(address)}` answer.features[0] && { lat: answer.features[0].geometry.coordinates[1], lng: answer.features[0].geometry.coordinates[0] }
MapTiler (free plan non-commercial) `https://api.maptiler.com/geocoding/${encodeURIComponent(address)}.json?limit=1&key=${encodeURIComponent(key)}` answer.features[0] && { lat: answer.features[0].center[1], lng: answer.features[0].center[0] }

Change pointIn’s parameter type to the new answer’s shape, the wait to the new geocoder’s rate, and drop the key check for a self-hosted geocoder that takes none.

A visitor’s address

The “My location” button needs a visitor who shares their position. For anyone who refuses, or is planning from somewhere else, a form of your own can take an address and sort the list by distance from there. Maplace.js sends nothing itself: the geocoder is yours.

<form id="from-address">
  <label for="address">Your address</label>
  <input id="address" name="address">
  <button type="submit" disabled>Sort by distance</button>
  <output></output>
</form>
// An address typed into your own form becomes the point the list measures from. `geocode` is yours;
// a blank address clears the point. The button stays disabled until this runs: a submit without it
// would put the address in the page's URL. Returns what stops listening.
import type { LatLng, Maplace } from "@maplacejs/maplace";

/** Your geocoder: the address's point, or `undefined` when it finds none. */
export type Geocode = (address: string) => Promise<LatLng | undefined>;

function partOf<Part extends Element>(form: HTMLFormElement, selector: string): Part {
  const part = form.querySelector<Part>(selector);
  if (!part) throw new Error(`The form needs an element matching ${selector}`);
  return part;
}

export function searchFromAddress(
  form: HTMLFormElement,
  map: Maplace,
  geocode: Geocode,
): () => void {
  const input = partOf<HTMLInputElement>(form, '[name="address"]');
  const status = partOf(form, "output");
  const button = partOf<HTMLButtonElement>(form, '[type="submit"]');
  let latest = 0;

  function measureFrom(point: LatLng): void {
    map.setOrigin(point);
    const { viewport } = map.getSnapshot();
    if (viewport) map.setView(point, viewport.zoom);
  }

  async function search(address: string, ask: number): Promise<void> {
    form.setAttribute("aria-busy", "true");
    const point = await geocode(address);
    if (ask !== latest) return;
    if (point) measureFrom(point);
    status.textContent = point ? `Nearest to ${address}` : "Address not found";
  }

  async function submitted(event: Event): Promise<void> {
    event.preventDefault();
    latest += 1;
    const ask = latest;
    status.textContent = "";
    const address = input.value.trim();
    try {
      if (address) await search(address, ask);
      else map.setOrigin(undefined);
    } catch (error) {
      console.error(error);
      if (ask === latest) status.textContent = "Search unavailable";
    } finally {
      if (ask === latest) form.removeAttribute("aria-busy");
    }
  }

  form.addEventListener("submit", submitted);
  button.disabled = false;
  return () => {
    button.disabled = true;
    form.removeEventListener("submit", submitted);
    latest += 1;
    form.removeAttribute("aria-busy");
  };
}

On <maplace-map>, the store is .maplace once the element is defined:

await customElements.whenDefined("maplace-map");
const map = document.querySelector("maplace-map").maplace;
searchFromAddress(document.querySelector("#from-address"), map, geocode);

That goes in one <script type="module">, after the recipe (its import type, types and export dropped) and your geocode. In React, call it in an effect, with the store from useMaplace() and a geocode declared outside the component, and return what it returns.

geocode runs in the visitor’s browser, so any key it holds is public, and most geocoders bill each search, which is why the form asks on submit and never per keystroke:

  • On Google: Maps JS’s geocoder, with the Geocoding API enabled in your key’s project, as a key restricted to Maps JS alone fails every search. Its results shown on a map must be on a Google map, and shown off one carry Google’s attribution (policies, read on 2026-11-01). It needs Maps JS on the page, so wait for the map first, await map.whenReady() before searchFromAddress: the button then stays disabled until the map opens, however long it is loading, held for consent or off-screen with loading="lazy". Not run here, as each search is billed:

    const geocode = async (address) => {
      const { Geocoder } = await google.maps.importLibrary("geocoding");
      const { results } = await new Geocoder().geocode({ address, fulfillOnZeroResults: true });
      return results[0]?.geometry.location.toJSON();
    };
  • On MapLibre: another geocoder (the table above has some), or your own server calling one, so the key stays there. OpenStreetMap-based results keep their attribution.

A typed address may be the visitor’s home, and it goes to that geocoder: say so in your privacy notice. The button starts disabled, as a submit before your script runs would put the address in the page’s URL, so a script that fails leaves the form unusable, not leaking. An answer arriving late can replace an origin set since by other means, such as “My location”, and the status keeps saying “Nearest to” the address if something else sets the origin afterwards. The recipe’s own checks use a stub geocoder; it hasn’t run against a real one.