# Filter by tags

Places with several tags: tick some to see those with all of them.

## How it works

A location has one `group`, its heading in the list, and as many `tags` as it needs. Tick a box and the map and the list keep the places with all the ticked tags; untick them all and every place is back. The boxes sit above the map, the list on it, top right.

- **HTML**: `tags="parking open-late"` on `<maplace-location>`, the tags split on spaces ([Location attributes](/element/#location-attributes)), `group-counts` on `<maplace-map>` for the numbers ([Map attributes](/element/#map-attributes)), and a script calling the element's `maplace.setFilter`.
- **Script** and **Bundler**: `tags: ["parking", "open-late"]` on a location ([Every location](/locations/#every-location)), `groupCounts` on the list ([List view options](/store/#list-view-options)), and [`setFilter({ tags })`](/store/#methods) with what is ticked: no tags ask for nothing, so no branch is needed for none.
- **React**: `<LocationList groupCounts />` and the `filter` prop of [`<MaplaceProvider>`](/react/#maplaceprovider), `filter={{ tags }}`, applied when its value changes.
- **With groups**: `setFilter({ groups: ["North"], tags: ["parking"] })` keeps what matches both; `setFilter(["North"])`, a list of groups alone, is what the [Dropdown of places](/examples/lists/menu/) example does.

## Code

### HTML on MapLibre

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- Places with several tags, in a list on the map under their one group; the checkboxes show those with all the ticked tags. -->
<p id="tags-maplibre-filters">
  <label><input type="checkbox" value="parking" /> Parking</label>
  <label><input type="checkbox" value="open-late" /> Open late</label>
</p>
<maplace-map id="tags-maplibre-map" list list-position="top-right" list-heading="Places" group-counts>
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome" group="Centre" tags="parking open-late"></maplace-location>
  <maplace-location location-id="bologna" lat="44.4949" lng="11.3426" title="Bologna" group="Centre"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan" group="North" tags="parking"></maplace-location>
  <maplace-location location-id="turin" lat="45.0703" lng="7.6869" title="Turin" group="North" tags="open-late"></maplace-location>
  <maplace-location location-id="naples" lat="40.8518" lng="14.2681" title="Naples" group="South" tags="parking open-late"></maplace-location>
</maplace-map>
<script>
  document.getElementById('tags-maplibre-filters').addEventListener('change', (event) => {
    const ticked = event.currentTarget.querySelectorAll(':checked');
    document.getElementById('tags-maplibre-map').maplace.setFilter({ tags: Array.from(ticked, (box) => box.value) });
  });
</script>
```

### HTML on Google

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- Places with several tags, in a list on the map under their one group; the checkboxes show those with all the ticked tags. -->
<p id="tags-filters">
  <label><input type="checkbox" value="parking" /> Parking</label>
  <label><input type="checkbox" value="open-late" /> Open late</label>
</p>
<maplace-map id="tags-map" api-key="YOUR_KEY" list list-position="top-right" list-heading="Places" group-counts>
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome" group="Centre" tags="parking open-late"></maplace-location>
  <maplace-location location-id="bologna" lat="44.4949" lng="11.3426" title="Bologna" group="Centre"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan" group="North" tags="parking"></maplace-location>
  <maplace-location location-id="turin" lat="45.0703" lng="7.6869" title="Turin" group="North" tags="open-late"></maplace-location>
  <maplace-location location-id="naples" lat="40.8518" lng="14.2681" title="Naples" group="South" tags="parking open-late"></maplace-location>
</maplace-map>
<script>
  document.getElementById('tags-filters').addEventListener('change', (event) => {
    const ticked = event.currentTarget.querySelectorAll(':checked');
    document.getElementById('tags-map').maplace.setFilter({ tags: Array.from(ticked, (box) => box.value) });
  });
</script>
```

### Script on MapLibre

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

```html
<!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, the checkboxes and what the map mounts on, and the map made with Maplace. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #tags-maplibre-script-map { height: 24rem; }
</style>
<p id="tags-maplibre-script-filters">
  <label><input type="checkbox" value="parking" /> Parking</label>
  <label><input type="checkbox" value="open-late" /> Open late</label>
</p>
<div id="tags-maplibre-script-map"></div>
<script type="module">
  const maplace = Maplace.createMapLibreMap("#tags-maplibre-script-map", {
    locations: [
      { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", group: "Centre", tags: ["parking", "open-late"] },
      { id: "bologna", lat: 44.4949, lng: 11.3426, title: "Bologna", group: "Centre" },
      { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", group: "North", tags: ["parking"] },
      { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin", group: "North", tags: ["open-late"] },
      { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples", group: "South", tags: ["parking", "open-late"] },
    ],
    list: { heading: "Places", groupCounts: true },
  });

  const filters = document.querySelector("#tags-maplibre-script-filters");
  filters?.addEventListener("change", () => {
    const ticked = filters.querySelectorAll(":checked");
    maplace.setFilter({ tags: Array.from(ticked, (box) => box.value) });
  });
</script>
```

### Script on Google

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

```html
<!doctype html>
<!-- A page of your own script: the CDN script, the checkboxes and 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>
  #tags-script-map { height: 24rem; }
</style>
<p id="tags-script-filters">
  <label><input type="checkbox" value="parking" /> Parking</label>
  <label><input type="checkbox" value="open-late" /> Open late</label>
</p>
<div id="tags-script-map"></div>
<script type="module">
  const maplace = Maplace.createGoogleMap("#tags-script-map", {
    apiKey: "YOUR_KEY",
    locations: [
      { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", group: "Centre", tags: ["parking", "open-late"] },
      { id: "bologna", lat: 44.4949, lng: 11.3426, title: "Bologna", group: "Centre" },
      { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", group: "North", tags: ["parking"] },
      { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin", group: "North", tags: ["open-late"] },
      { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples", group: "South", tags: ["parking", "open-late"] },
    ],
    list: { heading: "Places", groupCounts: true },
  });

  const filters = document.querySelector("#tags-script-filters");
  filters?.addEventListener("change", () => {
    const ticked = filters.querySelectorAll(":checked");
    maplace.setFilter({ tags: Array.from(ticked, (box) => box.value) });
  });
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/tags/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>
  #tags-maplibre-vanilla-map { height: 24rem; }
</style>
<p id="tags-maplibre-vanilla-filters">
  <label><input type="checkbox" value="parking" /> Parking</label>
  <label><input type="checkbox" value="open-late" /> Open late</label>
</p>
<div id="tags-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

const maplace = createMapLibreMap("#tags-maplibre-vanilla-map", {
  locations: [
    {
      id: "rome",
      lat: 41.9028,
      lng: 12.4964,
      title: "Rome",
      group: "Centre",
      tags: ["parking", "open-late"],
    },
    { id: "bologna", lat: 44.4949, lng: 11.3426, title: "Bologna", group: "Centre" },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", group: "North", tags: ["parking"] },
    { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin", group: "North", tags: ["open-late"] },
    {
      id: "naples",
      lat: 40.8518,
      lng: 14.2681,
      title: "Naples",
      group: "South",
      tags: ["parking", "open-late"],
    },
  ],
  list: { heading: "Places", groupCounts: true },
});

const filters = document.querySelector("#tags-maplibre-vanilla-filters");
filters?.addEventListener("change", () => {
  const ticked = filters.querySelectorAll<HTMLInputElement>(":checked");
  maplace.setFilter({ tags: Array.from(ticked, (box) => box.value) });
});
```

### Bundler on Google

`packages/maplace/examples/tags/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>
  #tags-vanilla-map { height: 24rem; }
</style>
<p id="tags-vanilla-filters">
  <label><input type="checkbox" value="parking" /> Parking</label>
  <label><input type="checkbox" value="open-late" /> Open late</label>
</p>
<div id="tags-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

const maplace = createGoogleMap("#tags-vanilla-map", {
  locations: [
    {
      id: "rome",
      lat: 41.9028,
      lng: 12.4964,
      title: "Rome",
      group: "Centre",
      tags: ["parking", "open-late"],
    },
    { id: "bologna", lat: 44.4949, lng: 11.3426, title: "Bologna", group: "Centre" },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", group: "North", tags: ["parking"] },
    { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin", group: "North", tags: ["open-late"] },
    {
      id: "naples",
      lat: 40.8518,
      lng: 14.2681,
      title: "Naples",
      group: "South",
      tags: ["parking", "open-late"],
    },
  ],
  list: { heading: "Places", groupCounts: true },
});

const filters = document.querySelector("#tags-vanilla-filters");
filters?.addEventListener("change", () => {
  const ticked = filters.querySelectorAll<HTMLInputElement>(":checked");
  maplace.setFilter({ tags: Array.from(ticked, (box) => box.value) });
});
```

### React on MapLibre

`packages/maplace/examples/tags/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>
  #tags-maplibre-react-root .map { height: 24rem; }
</style>
<div id="tags-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

const cities: Location[] = [
  {
    id: "rome",
    lat: 41.9028,
    lng: 12.4964,
    title: "Rome",
    group: "Centre",
    tags: ["parking", "open-late"],
  },
  { id: "bologna", lat: 44.4949, lng: 11.3426, title: "Bologna", group: "Centre" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", group: "North", tags: ["parking"] },
  { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin", group: "North", tags: ["open-late"] },
  {
    id: "naples",
    lat: 40.8518,
    lng: 14.2681,
    title: "Naples",
    group: "South",
    tags: ["parking", "open-late"],
  },
];
const CHOICES = [
  { tag: "parking", label: "Parking" },
  { tag: "open-late", label: "Open late" },
];

function Tags() {
  const [tags, setTags] = useState<readonly string[]>([]);
  return (
    <MaplaceProvider locations={cities} filter={{ tags }}>
      <p>
        {CHOICES.map(({ tag, label }) => (
          <Fragment key={tag}>
            <label>
              <input
                type="checkbox"
                checked={tags.includes(tag)}
                onChange={(event) =>
                  setTags(
                    event.target.checked ? [...tags, tag] : tags.filter((other) => other !== tag),
                  )
                }
              />{" "}
              {label}
            </label>{" "}
          </Fragment>
        ))}
      </p>
      <MaplaceMap createAdapter={createMapLibreAdapter} className="map">
        <LocationList heading="Places" groupCounts position="top-right" />
      </MaplaceMap>
    </MaplaceProvider>
  );
}

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

### React on Google

`packages/maplace/examples/tags/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>
  #tags-react-root .map { height: 24rem; }
</style>
<div id="tags-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

const cities: Location[] = [
  {
    id: "rome",
    lat: 41.9028,
    lng: 12.4964,
    title: "Rome",
    group: "Centre",
    tags: ["parking", "open-late"],
  },
  { id: "bologna", lat: 44.4949, lng: 11.3426, title: "Bologna", group: "Centre" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", group: "North", tags: ["parking"] },
  { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin", group: "North", tags: ["open-late"] },
  {
    id: "naples",
    lat: 40.8518,
    lng: 14.2681,
    title: "Naples",
    group: "South",
    tags: ["parking", "open-late"],
  },
];
const CHOICES = [
  { tag: "parking", label: "Parking" },
  { tag: "open-late", label: "Open late" },
];

function Tags() {
  const [tags, setTags] = useState<readonly string[]>([]);
  return (
    <MaplaceProvider locations={cities} filter={{ tags }}>
      <p>
        {CHOICES.map(({ tag, label }) => (
          <Fragment key={tag}>
            <label>
              <input
                type="checkbox"
                checked={tags.includes(tag)}
                onChange={(event) =>
                  setTags(
                    event.target.checked ? [...tags, tag] : tags.filter((other) => other !== tag),
                  )
                }
              />{" "}
              {label}
            </label>{" "}
          </Fragment>
        ))}
      </p>
      <MaplaceMap createAdapter={createGoogleAdapter} className="map">
        <LocationList heading="Places" groupCounts position="top-right" />
      </MaplaceMap>
    </MaplaceProvider>
  );
}

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