# Map styles

The provider's own map styles to choose from, and on Google the map-type control.

## How it works

The provider's own looks: on Google a light or dark map, or the visitor's system setting, with Google's map options; on MapLibre a choice of OpenFreeMap's styles, or any style's URL.

- **HTML**: on Google `color-scheme`, `map-id` and `map-options`, a change of `color-scheme` or `map-options` opening the map again ([Provider attributes](/google/#provider-attributes)); on MapLibre `map-style` and `map-options` ([Provider attributes](/maplibre/#provider-attributes)).
- **Script** and **Bundler**: `createGoogleAdapter({ mapId, colorScheme, mapOptions })` ([Map ID and styling](/google/#map-id-and-styling)) or `createMapLibreAdapter({ mapStyle, mapOptions })` ([Styles and tiles](/maplibre/#styles-and-tiles)), and `attach`; a new look is a new adapter, attached where the last one was ([Methods](/store/#methods)).
- **React**: the same adapters through `createAdapter`, and a `key` on `<MaplaceMap>` that changes with the look, so a new one opens ([`<MaplaceMap>`](/react/#maplacemap)).

## Code

### HTML on MapLibre

`packages/maplace/examples/styled/maplibre/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- MapLibre's own look: a style, here one of OpenFreeMap's, and MapLibre's map options (here a
     compact attribution). Choosing a style opens the map again in it, where it was. Any style URL
     works in map-style: MapTiler's, Stadia's, your own. -->
<p><label for="styled-maplibre-style">Map style</label> <select id="styled-maplibre-style" autocomplete="off">
  <option value="https://tiles.openfreemap.org/styles/bright">Bright</option>
  <option value="https://tiles.openfreemap.org/styles/liberty">Liberty</option>
  <option value="https://tiles.openfreemap.org/styles/positron">Positron</option>
  <option value="https://tiles.openfreemap.org/styles/dark">Dark</option>
</select></p>
<maplace-map id="styled-maplibre-map" map-style="https://tiles.openfreemap.org/styles/bright"
  map-options='{"attributionControl":{"compact":true}}'>
  <maplace-location location-id="lisbon" lat="38.7223" lng="-9.1393" title="Lisbon"></maplace-location>
  <maplace-location location-id="porto" lat="41.1579" lng="-8.6291" title="Porto"></maplace-location>
  <maplace-location location-id="coimbra" lat="40.2033" lng="-8.4103" title="Coimbra"></maplace-location>
  <maplace-location location-id="faro" lat="37.0194" lng="-7.9304" title="Faro"></maplace-location>
</maplace-map>
<script>
  document.getElementById('styled-maplibre-style').addEventListener('change', (event) => {
    document.getElementById('styled-maplibre-map').setAttribute('map-style', event.currentTarget.value);
  });
</script>
```

### HTML on Google

`packages/maplace/examples/styled/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- Google's own look: a light or dark map, or the reader's system scheme, and Google's map options
     (here the map-type control). Choosing a scheme opens the map again in it, where it was.
     A map's Cloud styling hangs on its map ID: put your own in map-id. -->
<p><label for="styled-scheme">Map style</label> <select id="styled-scheme" autocomplete="off">
  <option value="light">Light</option>
  <option value="dark">Dark</option>
  <option value="follow-system">Follow the system</option>
</select></p>
<maplace-map id="styled-map" api-key="YOUR_KEY" map-id="DEMO_MAP_ID" color-scheme="light"
  map-options='{"mapTypeControl":true}'>
  <maplace-location location-id="lisbon" lat="38.7223" lng="-9.1393" title="Lisbon"></maplace-location>
  <maplace-location location-id="porto" lat="41.1579" lng="-8.6291" title="Porto"></maplace-location>
  <maplace-location location-id="coimbra" lat="40.2033" lng="-8.4103" title="Coimbra"></maplace-location>
  <maplace-location location-id="faro" lat="37.0194" lng="-7.9304" title="Faro"></maplace-location>
</maplace-map>
<script>
  document.getElementById('styled-scheme').addEventListener('change', (event) => {
    document.getElementById('styled-map').setAttribute('color-scheme', event.currentTarget.value);
  });
</script>
```

### Script on MapLibre

`packages/maplace/examples/styled/maplibre/script.html`

```html
<!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, the style select and what the map mounts on, and the map made with Maplace's store and MapLibre adapter. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #styled-maplibre-script-map { height: 24rem; }
</style>
<p><label for="styled-maplibre-script-style">Map style</label> <select id="styled-maplibre-script-style" autocomplete="off">
  <option value="https://tiles.openfreemap.org/styles/bright">Bright</option>
  <option value="https://tiles.openfreemap.org/styles/liberty">Liberty</option>
  <option value="https://tiles.openfreemap.org/styles/positron">Positron</option>
  <option value="https://tiles.openfreemap.org/styles/dark">Dark</option>
</select></p>
<div id="styled-maplibre-script-map"></div>
<script type="module">
  const locations = [
    { id: "lisbon", lat: 38.7223, lng: -9.1393, title: "Lisbon" },
    { id: "porto", lat: 41.1579, lng: -8.6291, title: "Porto" },
    { id: "coimbra", lat: 40.2033, lng: -8.4103, title: "Coimbra" },
    { id: "faro", lat: 37.0194, lng: -7.9304, title: "Faro" },
  ];

  /**
   * MapLibre's own look: a style, here one of OpenFreeMap's the page offers (any style URL works:
   * MapTiler's, Stadia's, your own), with a compact attribution.
   */
  const adapterIn = (mapStyle) =>
    Maplace.createMapLibreAdapter({
      mapStyle,
      mapOptions: { attributionControl: { compact: true } },
    });

  const maplace = Maplace.createMaplace({ locations });
  const styleSelect = document.querySelector("#styled-maplibre-script-style");
  let detach = maplace.attach(adapterIn(styleSelect.value), "#styled-maplibre-script-map");

  // A map's style is set when it opens: choosing one opens a new map where this one was.
  styleSelect.addEventListener("change", () => {
    const { viewport } = maplace.getSnapshot();
    detach();
    if (viewport) maplace.setView(viewport.center, viewport.zoom);
    detach = maplace.attach(adapterIn(styleSelect.value), "#styled-maplibre-script-map");
  });
</script>
```

### Script on Google

`packages/maplace/examples/styled/script.html`

```html
<!doctype html>
<!-- A page of your own script: the CDN script, the scheme select and what the map mounts on, and the map made with Maplace's store and Google adapter, which adds Maps JS with your key. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<style>
  #styled-script-map { height: 24rem; }
</style>
<p><label for="styled-script-scheme">Map style</label> <select id="styled-script-scheme" autocomplete="off">
  <option value="light">Light</option>
  <option value="dark">Dark</option>
  <option value="follow-system">Follow the system</option>
</select></p>
<div id="styled-script-map"></div>
<script type="module">
  const locations = [
    { id: "lisbon", lat: 38.7223, lng: -9.1393, title: "Lisbon" },
    { id: "porto", lat: 41.1579, lng: -8.6291, title: "Porto" },
    { id: "coimbra", lat: 40.2033, lng: -8.4103, title: "Coimbra" },
    { id: "faro", lat: 37.0194, lng: -7.9304, title: "Faro" },
  ];

  /**
   * Google's own look: a light or dark map, or the reader's system scheme, with the map-type
   * control. A map's Cloud styling hangs on its map ID: put your own in `mapId`.
   */
  const adapterIn = (colorScheme) =>
    Maplace.createGoogleAdapter({
      apiKey: "YOUR_KEY",
      mapId: "DEMO_MAP_ID",
      colorScheme,
      mapOptions: { mapTypeControl: true },
    });

  const maplace = Maplace.createMaplace({ locations });
  const schemeSelect = document.querySelector("#styled-script-scheme");
  let detach = maplace.attach(adapterIn(schemeSelect.value), "#styled-script-map");

  // A map's colour scheme is set when it opens: choosing one opens a new map where this one was.
  schemeSelect.addEventListener("change", () => {
    const { viewport } = maplace.getSnapshot();
    detach();
    if (viewport) maplace.setView(viewport.center, viewport.zoom);
    detach = maplace.attach(adapterIn(schemeSelect.value), "#styled-script-map");
  });
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/styled/maplibre/vanilla.html`

```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>
  #styled-maplibre-vanilla-map { height: 24rem; }
</style>
<p><label for="styled-maplibre-vanilla-style">Map style</label> <select id="styled-maplibre-vanilla-style" autocomplete="off">
  <option value="https://tiles.openfreemap.org/styles/bright">Bright</option>
  <option value="https://tiles.openfreemap.org/styles/liberty">Liberty</option>
  <option value="https://tiles.openfreemap.org/styles/positron">Positron</option>
  <option value="https://tiles.openfreemap.org/styles/dark">Dark</option>
</select></p>
<div id="styled-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/styled/maplibre/vanilla.ts`

```ts
import "maplibre-gl/dist/maplibre-gl.css";
import { createMaplace, type Location } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";

const locations: Location[] = [
  { id: "lisbon", lat: 38.7223, lng: -9.1393, title: "Lisbon" },
  { id: "porto", lat: 41.1579, lng: -8.6291, title: "Porto" },
  { id: "coimbra", lat: 40.2033, lng: -8.4103, title: "Coimbra" },
  { id: "faro", lat: 37.0194, lng: -7.9304, title: "Faro" },
];

/**
 * MapLibre's own look: a style, here one of OpenFreeMap's the page offers (any style URL works:
 * MapTiler's, Stadia's, your own), with a compact attribution.
 */
const adapterIn = (mapStyle: string) =>
  createMapLibreAdapter({
    mapStyle,
    mapOptions: { attributionControl: { compact: true } },
  });

const maplace = createMaplace({ locations });
const styleSelect = document.querySelector("#styled-maplibre-vanilla-style") as HTMLSelectElement;
let detach = maplace.attach(adapterIn(styleSelect.value), "#styled-maplibre-vanilla-map");

// A map's style is set when it opens: choosing one opens a new map where this one was.
styleSelect.addEventListener("change", () => {
  const { viewport } = maplace.getSnapshot();
  detach();
  if (viewport) maplace.setView(viewport.center, viewport.zoom);
  detach = maplace.attach(adapterIn(styleSelect.value), "#styled-maplibre-vanilla-map");
});
```

### Bundler on Google

`packages/maplace/examples/styled/vanilla.html`

```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>
  #styled-vanilla-map { height: 24rem; }
</style>
<p><label for="styled-vanilla-scheme">Map style</label> <select id="styled-vanilla-scheme" autocomplete="off">
  <option value="light">Light</option>
  <option value="dark">Dark</option>
  <option value="follow-system">Follow the system</option>
</select></p>
<div id="styled-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/styled/vanilla.ts`

```ts
import { createMaplace, type Location } from "@maplacejs/maplace";
import { createGoogleAdapter, type GoogleAdapterOptions } from "@maplacejs/maplace/google";

type ColorScheme = NonNullable<GoogleAdapterOptions["colorScheme"]>;

const locations: Location[] = [
  { id: "lisbon", lat: 38.7223, lng: -9.1393, title: "Lisbon" },
  { id: "porto", lat: 41.1579, lng: -8.6291, title: "Porto" },
  { id: "coimbra", lat: 40.2033, lng: -8.4103, title: "Coimbra" },
  { id: "faro", lat: 37.0194, lng: -7.9304, title: "Faro" },
];

/**
 * Google's own look: a light or dark map, or the reader's system scheme, with the map-type
 * control. A map's Cloud styling hangs on its map ID: put your own in `mapId`.
 */
const adapterIn = (colorScheme: ColorScheme) =>
  createGoogleAdapter({ mapId: "DEMO_MAP_ID", colorScheme, mapOptions: { mapTypeControl: true } });

const maplace = createMaplace({ locations });
const schemeSelect = document.querySelector("#styled-vanilla-scheme") as HTMLSelectElement;
const chosenScheme = () => schemeSelect.value as ColorScheme;
let detach = maplace.attach(adapterIn(chosenScheme()), "#styled-vanilla-map");

// A map's colour scheme is set when it opens: choosing one opens a new map where this one was.
schemeSelect.addEventListener("change", () => {
  const { viewport } = maplace.getSnapshot();
  detach();
  if (viewport) maplace.setView(viewport.center, viewport.zoom);
  detach = maplace.attach(adapterIn(chosenScheme()), "#styled-vanilla-map");
});
```

### React on MapLibre

`packages/maplace/examples/styled/maplibre/react.html`

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

`packages/maplace/examples/styled/maplibre/react.tsx`

```tsx
import "maplibre-gl/dist/maplibre-gl.css";
import type { Location } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { MaplaceMap, MaplaceProvider, useMaplace } from "@maplacejs/maplace/react";
import { type ChangeEvent, StrictMode, useState } from "react";
import { createRoot } from "react-dom/client";

/** OpenFreeMap's styles, by name; any style URL works: MapTiler's, Stadia's, your own. */
const STYLES = {
  Bright: "https://tiles.openfreemap.org/styles/bright",
  Liberty: "https://tiles.openfreemap.org/styles/liberty",
  Positron: "https://tiles.openfreemap.org/styles/positron",
  Dark: "https://tiles.openfreemap.org/styles/dark",
} as const;

const places: Location[] = [
  { id: "lisbon", lat: 38.7223, lng: -9.1393, title: "Lisbon" },
  { id: "porto", lat: 41.1579, lng: -8.6291, title: "Porto" },
  { id: "coimbra", lat: 40.2033, lng: -8.4103, title: "Coimbra" },
  { id: "faro", lat: 37.0194, lng: -7.9304, title: "Faro" },
];

/** MapLibre's own look: a style, with a compact attribution. */
const adapterIn = (mapStyle: string) => () =>
  createMapLibreAdapter({
    mapStyle,
    mapOptions: { attributionControl: { compact: true } },
  });

/** The style's select: the store keeps where the map is, for the map opened in the new style. */
function StyleSelect({
  mapStyle,
  onChoose,
}: {
  readonly mapStyle: string;
  readonly onChoose: (mapStyle: string) => void;
}) {
  const maplace = useMaplace();
  const choose = (event: ChangeEvent<HTMLSelectElement>) => {
    const { viewport } = maplace.getSnapshot();
    if (viewport) maplace.setView(viewport.center, viewport.zoom);
    onChoose(event.currentTarget.value);
  };
  return (
    <p>
      <label htmlFor="styled-maplibre-react-style">Map style</label>{" "}
      <select
        id="styled-maplibre-react-style"
        autoComplete="off"
        value={mapStyle}
        onChange={choose}
      >
        {Object.entries(STYLES).map(([name, url]) => (
          <option key={url} value={url}>
            {name}
          </option>
        ))}
      </select>
    </p>
  );
}

function Styled() {
  const [mapStyle, setMapStyle] = useState<string>(STYLES.Bright);
  return (
    <MaplaceProvider locations={places}>
      <StyleSelect mapStyle={mapStyle} onChoose={setMapStyle} />
      {/* A map's style is set when it opens: a new key opens a new one. */}
      <MaplaceMap key={mapStyle} createAdapter={adapterIn(mapStyle)} className="map" />
    </MaplaceProvider>
  );
}

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

### React on Google

`packages/maplace/examples/styled/react.html`

```html
<!doctype html>
<!-- The page react.tsx renders into: 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>
  #styled-react-root .map { height: 24rem; }
</style>
<div id="styled-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/styled/react.tsx`

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

type ColorScheme = NonNullable<GoogleAdapterOptions["colorScheme"]>;

const SCHEMES = {
  light: "Light",
  dark: "Dark",
  "follow-system": "Follow the system",
} satisfies Record<ColorScheme, string>;

const places: Location[] = [
  { id: "lisbon", lat: 38.7223, lng: -9.1393, title: "Lisbon" },
  { id: "porto", lat: 41.1579, lng: -8.6291, title: "Porto" },
  { id: "coimbra", lat: 40.2033, lng: -8.4103, title: "Coimbra" },
  { id: "faro", lat: 37.0194, lng: -7.9304, title: "Faro" },
];

/**
 * Google's own look: a light or dark map, or the reader's system scheme, with the map-type
 * control. A map's Cloud styling hangs on its map ID: put your own in `mapId`.
 */
const adapterIn = (colorScheme: ColorScheme) => () =>
  createGoogleAdapter({ mapId: "DEMO_MAP_ID", colorScheme, mapOptions: { mapTypeControl: true } });

/** The scheme's select: the store keeps where the map is, for the map opened in the new scheme. */
function SchemeSelect({
  scheme,
  onChoose,
}: {
  readonly scheme: ColorScheme;
  readonly onChoose: (scheme: ColorScheme) => void;
}) {
  const maplace = useMaplace();
  const choose = (event: ChangeEvent<HTMLSelectElement>) => {
    const { viewport } = maplace.getSnapshot();
    if (viewport) maplace.setView(viewport.center, viewport.zoom);
    onChoose(event.currentTarget.value as ColorScheme);
  };
  return (
    <p>
      <label htmlFor="styled-react-scheme">Map style</label>{" "}
      <select id="styled-react-scheme" autoComplete="off" value={scheme} onChange={choose}>
        {Object.entries(SCHEMES).map(([value, label]) => (
          <option key={value} value={value}>
            {label}
          </option>
        ))}
      </select>
    </p>
  );
}

function Styled() {
  const [scheme, setScheme] = useState<ColorScheme>("light");
  return (
    <MaplaceProvider locations={places}>
      <SchemeSelect scheme={scheme} onChoose={setScheme} />
      {/* A map's colour scheme is set when it opens: a new key opens a new one. */}
      <MaplaceMap key={scheme} createAdapter={adapterIn(scheme)} className="map" />
    </MaplaceProvider>
  );
}

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