---
name: maplace
description: "Write Maplace.js maps: a list of locations becomes a Google Maps or MapLibre map with a synced list, through the maplace-map element, a CDN script, the npm package `@maplacejs/maplace` or its React binding. Use it when someone wants a map with markers, circles, polylines or polygons on a page, or names Maplace.js, maplace, maplacejs or @maplacejs/maplace. It teaches 1.0's API, not the 0.2 jQuery plugin's."
---

# Make a map with Maplace.js

Maplace.js turns a list of locations into a map with a synced list, on Google Maps or MapLibre. It keeps selection and hover in one store the map, the list and your code read.

This is a rewrite. There is no jQuery and no `new Maplace(options).Load()`: that is 0.2, so never write it. To move a 0.2 page, read [Migrating](https://maplacejs.com/migrating/).

The docs:

- [Getting started](https://maplacejs.com/getting-started/): Put a Google Map or a MapLibre map with markers and a synced list on a website: one script tag, or npm and React.
- [Setup](https://maplacejs.com/setup/): What a map needs: on Google a key, Maps JS and, for production, a map ID; on MapLibre maplibre-gl and a style. With the element, a script of your own, or npm.
- [Element](https://maplacejs.com/element/): The maplace-map and maplace-location elements: attributes, properties, events, providers and list views.
- [Locations](https://maplacejs.com/locations/): Every location field, by type: markers, circles, polylines, polygons and multipolygons, with what each one draws and takes.
- [Store](https://maplacejs.com/store/): The headless store: its options, methods, state and events, the first view of a map, and its list view.
- [Google](https://maplacejs.com/google/): The Google Maps adapter: options, your own map, loading Maps JS, map IDs, routes and clustering.
- [MapLibre](https://maplacejs.com/maplibre/): The MapLibre adapter: options, your own map, styles and tiles, loading maplibre-gl, zoom, clustering, and what differs from Google.
- [React](https://maplacejs.com/react/): The React binding of Maplace.js: provider, map, list, map controls and the hook that reads the store.
- [Styling](https://maplacejs.com/styling/): Maplace.js's default styles, turning them off, and the classes to style its markup by.
- [Accessibility](https://maplacejs.com/accessibility/): What Maplace.js does for a keyboard and a screen reader, what was tested and on what, and what wasn't.
- [API](https://maplacejs.com/api/): Every export of every entry of the @maplacejs/maplace package, with its error codes and the capabilities of each map provider.
- [Migrating](https://maplacejs.com/migrating/): Every 0.2 option, location field, method and callback, and what 1.0 does with it.

## Install

Google Maps:

```sh
npm install @maplacejs/maplace
```

```html
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1.2.0/dist/maplace-element.iife.js"
  integrity="sha384-OgwZw1NQ78VKxQUXntJyiiRILF/Ck2chxPi2kbY+gNOcSqZIIsBVXI1BAPbqs6LV" crossorigin="anonymous"></script>
```

MapLibre:

```sh
npm install @maplacejs/maplace maplibre-gl
```

```html
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1.2.0/dist/maplace-element-maplibre.iife.js"
  integrity="sha384-NTx1K+93ZQC7ezi/smTAvSpiQCrdWid6IfMLQuIS6oT/63JARr9b+gD1devKzZqV" crossorigin="anonymous"></script>
```

`@maplacejs/maplace@1` follows the latest 1.x and can't carry an integrity hash: pin in production. Google's plain script has no clusterer; for `cluster`, this one instead:

```html
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1.2.0/dist/maplace-element-cluster.iife.js"
  integrity="sha384-nYnk30aW5TZxhlK3odeU4GRQiVdUxmZ1+GsvV2Ld4/8H7cEwXWsseZPHy8n+jfXc" crossorigin="anonymous"></script>
```

## What a map needs

On Google, two different things, easy to mix up:

| | API key | Map ID |
|---|---|---|
| Where | the element's `api-key`, or `key` in Google's loader | the element's `map-id`, the adapter's `mapId` |
| What it does | lets your site load Maps JS, and bills your Google project | picks the map's configuration: advanced markers, Cloud styling |
| In the examples | `YOUR_KEY`, a placeholder: nothing loads until you put yours in | left out: the map uses Google's `DEMO_MAP_ID` |
| Needed | yes, always | no |
| Kept safe by | restricting it to your site's addresses: it is in your page for anyone to read | nothing: it is public |

- **The key** is your Google Maps JavaScript API key: Google's [Get an API key](https://developers.google.com/maps/documentation/javascript/get-api-key) says how to make one and restrict it to your site.
- **The map ID** defaults to `DEMO_MAP_ID`, Google's public map ID for development. A map on it warns once in the console that it isn't for production.
- **For production**, make a map ID of your own (Google's [map IDs](https://developers.google.com/maps/documentation/get-map-id)) and set it. It is also where the map's Cloud styling lives, besides a colour scheme ([map ID and styling](https://maplacejs.com/google/#map-id-and-styling)).

Google checks the key as the first map opens. A key it refuses (an invalid key, a referrer the key doesn't allow, the API or billing not enabled, a quota used up) is a `provider-auth-failed` error for every map on the page, and the map shows Google's message. A missing key isn't refused: Google draws the map and logs `ApiProjectMapError`, so Maplace.js reports nothing ([when Google refuses](https://maplacejs.com/google/#when-google-refuses)).

On MapLibre a map's look and its tiles come from its style: a URL (or a JSON style object) the element's `map-style` or the adapter's `mapStyle` takes. Left out, it is OpenFreeMap's `bright` style: free, no key, OpenStreetMap data.

Another provider's style URL works the same way, its key in the URL where it needs one, and kept safe as that provider says. A style its server refuses (HTTP 401 or 403) is `provider-auth-failed`, and one that fails to load is `provider-load-failed` ([styles and tiles](https://maplacejs.com/maplibre/#styles-and-tiles)).

A MapLibre page has to be opened from a web server, and a local one such as `http://localhost` is fine. Opened directly as a file (`file://`), the map can't start its worker and says it couldn't load.

From npm the page loads Maps JS: pass `apiKey` to `createGoogleMap`, or load Google's loader first. A map fills its container, so give the container a height; the element is 24rem tall by default.

## The element

In a bundled app, `import "@maplacejs/maplace/element/google"` or `"@maplacejs/maplace/element/maplibre"` defines the same elements; on MapLibre, also import `maplibre-gl/dist/maplibre-gl.css`.

```html
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<maplace-map api-key="YOUR_KEY" list>
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
</maplace-map>
```

```html
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<maplace-map list>
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
</maplace-map>
```

A shape's points don't fit an attribute: a polygon or polyline goes in a JSON script, or the `locations` property.

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- An editable area; edits are written back and announced. -->
<maplace-map id="polygon-map" api-key="YOUR_KEY">
  <script type="application/json">
    [{ "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 }] }]
  </script>
</maplace-map>
<script>
  document.getElementById('polygon-map').addEventListener('maplace-locationchange', (event) => save(event.detail.location));
</script>
```

`save` is your own function.

- `<maplace-map>` reads `list`, `list-position`, `fit-all`, `fit-all-label`, `list-heading`, `group-counts`, `list-scope`, `list-sort`, `distance-unit`, `area-only-label`, `show-all-label`, `empty-area-label`, `search`, `search-label`, `no-matches-label`, `matches-label`, `group-filter`, `group-filter-label`, `center`, `zoom`, `heatmap`, `heatmap-max-zoom`, `provider`, `cluster`, `skip-map-label`, `selected-label`, `open-in-maps-link`, `open-in-maps-label`, `directions-link`, `directions-label`, `popup-open-on`, `hold`, `loading`, `load-label`, `failure-label`, `load-from-label`, `selected-id`, `url-state`, `my-location`, `my-location-label`, `my-location-unavailable-label`, `my-location-position`.
- On Google it also reads `map-id`, `nonce`, `color-scheme`, `map-options`, `api-key`, `version`, `language`, `region`.
- On MapLibre it also reads `map-style`, `map-options`, `globe`, `globe-position`, `globe-label`.
- `<maplace-location>` reads `location-id`, `lat`, `lng`, `title`, `type`, `group`, `tags`, `search-text`, `radius`, `icon`, `zoom`, `weight`, `listed`, `editable`, `active`, `shape-style`, `selected-style`, `hovered-style`, `active-style`.
- `<maplace-map>`'s properties are `locations`, `route`, `sanitize`, `computeRoute`, `maplace`, `loadState`, `release`.

What each does: [the element](https://maplacejs.com/element/).

## A script of your own

The CDN script also sets the page's `Maplace`.

```html
<!doctype html>
<!-- A page of your own script: the CDN script, what the map mounts on, and the map made with Maplace, which adds Maps JS with your key. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<style>
  #simple-script-map { height: 24rem; }
</style>
<div id="simple-script-map"></div>
<script type="module">
  Maplace.createGoogleMap("#simple-script-map", {
    apiKey: "YOUR_KEY",
    locations: [{ id: "london", lat: 51.5074, lng: -0.1278, title: "London" }],
  });
</script>
```

The MapLibre script's `Maplace` has `createMapLibreMap`, called the same way.

## npm and a bundler

Each module runs on a page like this one.

```html
<!doctype html>
<!-- The page vanilla.ts runs on: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->
<script>
  (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
    key: "YOUR_KEY",
    v: "weekly",
  });
</script>
<style>
  #simple-vanilla-map { height: 24rem; }
</style>
<div id="simple-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

```ts
import { createGoogleMap } from "@maplacejs/maplace/google";

createGoogleMap("#simple-vanilla-map", {
  locations: [{ id: "london", lat: 51.5074, lng: -0.1278, title: "London" }],
});
```

```html
<!doctype html>
<!-- The page vanilla.ts runs on: what the module mounts on, and the module, which brings maplibre-gl and its stylesheet. -->
<style>
  #simple-maplibre-vanilla-map { height: 24rem; }
</style>
<div id="simple-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

```ts
import "maplibre-gl/dist/maplibre-gl.css";
import { createMapLibreMap } from "@maplacejs/maplace/maplibre";

createMapLibreMap("#simple-maplibre-vanilla-map", {
  locations: [{ id: "london", lat: 51.5074, lng: -0.1278, title: "London" }],
});
```

`createGoogleMap` and `createMapLibreMap` are `createMaplace(options)` then `attach(adapter, container)` in one call.

## React

```tsx
import type { Location } from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

const london: Location[] = [{ id: "london", lat: 51.5074, lng: -0.1278, title: "London" }];

function Simple() {
  return (
    <MaplaceProvider locations={london}>
      <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("simple-react-root") as HTMLElement).render(
  <StrictMode>
    <Simple />
  </StrictMode>,
);
```

It runs on a page like the npm one: an element with the id it renders into, a height for its `.map`, and, on Google, Maps JS loaded. On MapLibre it differs by `createMapLibreAdapter` from `@maplacejs/maplace/maplibre` and by importing `maplibre-gl/dist/maplibre-gl.css`.

- `MaplaceProvider` takes `locations`, `defaultSelectedId`, `children`, `selectedId`, `filter`, `route`, `sanitize`, `popup`, `style`, `selectedStyle`, `hoveredStyle`, `activeStyle`, `cluster`, `heatmap`, `view`, `skipMapLabel`, `selectedLabel`.
- `MaplaceMap` takes `createAdapter`, `className`, `children`, `popupContent`, `markerIcon`.
- `LocationList` takes `as`, `groupHeadings`, `groupCounts`, `fitAll`, `fitAllLabel`, `label`, `heading`, `scope`, `sort`, `distanceUnit`, `areaOnlyLabel`, `showAllLabel`, `emptyAreaLabel`, `search`, `searchLabel`, `noMatchesLabel`, `matchesLabel`, `groupFilter`, `groupFilterLabel`, `children`, `position`.
- `MapControl` takes `position`, `children`.
- `MyLocation` takes `position`, `label`, `unavailableLabel`.

Inside the provider, `useMaplace` gives a component the store.

## Locations

```ts
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));
```

- Every location has `id`, `type`, `title`, `content`, `html`, `group`, `searchText`, `tags`, `zoom`, `visible`, `listed`, `editable`, `data`.
- A marker adds `lat`, `lng`, `icon`, `weight`.
- A circle adds `center`, `radius`, `style`, `selectedStyle`, `hoveredStyle`, `active`, `activeStyle`.
- A polyline adds `path`, `curve`, `geodesic`, `progress`, `travelledStyle`, `style`, `selectedStyle`, `hoveredStyle`, `active`, `activeStyle`.
- A polygon adds `path`, `holes`, `style`, `selectedStyle`, `hoveredStyle`, `active`, `activeStyle`.
- A multipolygon (several polygons, one location, not editable) adds `polygons`, `style`, `selectedStyle`, `hoveredStyle`, `active`, `activeStyle`, each polygon a `path` and optional `holes`.
- A style has `stroke`, `strokeOpacity`, `strokeWidth`, `strokeDash`, `fill`, `fillOpacity`: `strokeDash` (`"solid"`, `"dashed"`, `"dotted"`) on a polyline's or the route's only, `fill` and `fillOpacity` on a circle's or polygon's only.

## Options

- `createMaplace` takes `locations`, `selectedId`, `sanitize`, `popup`, `style`, `selectedStyle`, `hoveredStyle`, `activeStyle`, `cluster`, `heatmap`, `view`, `skipMapLabel`, `selectedLabel`.
- `popup` takes `maxWidth`, `offset`, `openOn`, `openInMapsLink`, `openInMapsLabel`, `directionsLink`, `directionsLabel`.
- The store's methods are `subscribe`, `getSnapshot`, `setLocations`, `select`, `hover`, `setFilter`, `fitAll`, `fitBounds`, `setView`, `setRoute`, `setOrigin`, `on`, `attach`, `whenReady`, `destroy`.
- `createGoogleMap` adds `mapId`, `colorScheme`, `mapOptions`, `apiKey`, `version`, `language`, `region`, `nonce`, `list`, `myLocation`, `list.position`, `list.container`, `myLocation.position`.
- `createMapLibreMap` adds `mapStyle`, `mapOptions`, `globe`, `computeRoute`, `list`, `myLocation`, `list.position`, `list.container`, `myLocation.position`, `globe.position`, `globe.label`.

A location's `html` needs `sanitize`.

## Adapters and capabilities

A capability is a feature an adapter may or may not support; using one the adapter lacks is `unsupported-capability`. Google has all six; MapLibre has `route` only with your own routing, as it has none ([routes](https://maplacejs.com/maplibre/#routes)).

| Capability | What it allows |
|---|---|
| `route` | `setRoute`, the element's `route` and React's `route` prop |
| `cluster` | The `cluster` option |
| `circle` | Circle locations |
| `edit` | `editable` locations |
| `multipolygon` | Multipolygon locations (1.2); an adapter written for 1.0 lacks it, so the store refuses them there |
| `heatmap` | The `heatmap` option (1.2), drawn by maplace on both providers; an adapter written for 1.0 lacks it |

## Events and errors

Events: [the store's](https://maplacejs.com/store/#events), [the element's](https://maplacejs.com/element/#events), [React's props](https://maplacejs.com/react/#event-props).

Errors: [what they carry](https://maplacejs.com/api/#errors), [misuse codes](https://maplacejs.com/api/#misuse-codes), [runtime failures](https://maplacejs.com/api/#runtime-failures).

## The API's rules

- camelCase throughout; verbs for methods, nouns for types, one word per concept, and no two ways to do the same thing.
- At most two positional arguments, then an options object; never a boolean flag: `select(id, { pan: false })`, not `select(id, false)`.
- Absence is `undefined`, never `null`.
- Views know only the store, adapters know only their host, and only the element (or your code) wires them together.

The full rules are in [RFC §3](https://github.com/danielemoraschi/maplace.js/blob/5dd17eac33e258107f91c7a4d4d05bc2673e17bd/docs/rfc-1.0.md#rules-the-api-follows).

## Mistakes to avoid

- Writing 0.2: no jQuery, no `new Maplace(options).Load()`.
- A map with no height: it fills its container, so give the container one (`<maplace-map>` has one unless unstyled).
- On Google, no key: a key is always needed, in the element's `api-key`, `createGoogleMap`'s `apiKey`, or `key` in Google's loader. A missing key raises no error: Google draws the map and only logs `ApiProjectMapError`. Without `map-id` or `mapId` the map runs on `DEMO_MAP_ID`, which isn't for production.
- Points as GeoJSON's `[lng, lat]`: a location's points are `{ lat, lng }`; turn a FeatureCollection into locations with `locationsFromGeoJSON`.
- `html` without `sanitize`: that is `missing-sanitizer`. `content`, a string shown as text, a node or a function, needs none.
- Loading before consent: give the element `hold`, and call `release()` once the visitor agrees; from npm, call `createGoogleMap` or `createMapLibreMap`, or render React's map, only then.
