# Sort by distance

A button on the map that sorts the list by distance from the visitor.

## How it works

The **My location** button on the map asks the browser for the visitor's position only when it is pressed, then sorts the list nearest first, each entry saying how far in a straight line, marks the place with a dot and moves the map there.

- **Note**: if the visitor refuses, or the page isn't on HTTPS, a line under the button says "Location unavailable" and nothing else changes.
- **HTML**: `list-sort="distance"` and `my-location` on `<maplace-map>`, with `distance-unit="mile"` for miles ([Map attributes](/element/#map-attributes)).
- **Script** and **Bundler**: `sort: "distance"` in `list`, and `myLocation: true` in the map's options ([Distances](/store/#distances)).
- **React**: `<LocationList sort="distance" />`, and `<MyLocation />` inside the `<MaplaceMap>` ([`<MyLocation>`](/react/#mylocation)).
- **Another point**: [`setOrigin`](/store/#methods) takes any point, so a click measures from there: `map.on("mapClick", ({ position }) => map.setOrigin(position))`, and [a form of your own](/locations/#a-visitors-address) measures from a typed address.

## Code

### HTML on MapLibre

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- Places in a list beside the map; the "My location" button on the map sorts it nearest first, each entry saying how far. -->
<maplace-map id="nearest-maplibre-map" list list-sort="distance" my-location>
  <maplace-location location-id="london" lat="51.5074" lng="-0.1278" title="London"></maplace-location>
  <maplace-location location-id="bristol" lat="51.4545" lng="-2.5879" title="Bristol"></maplace-location>
  <maplace-location location-id="birmingham" lat="52.4862" lng="-1.8904" title="Birmingham"></maplace-location>
  <maplace-location location-id="manchester" lat="53.4808" lng="-2.2426" title="Manchester"></maplace-location>
  <maplace-location location-id="leeds" lat="53.8008" lng="-1.5491" title="Leeds"></maplace-location>
</maplace-map>
```

### HTML on Google

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- Places in a list beside the map; the "My location" button on the map sorts it nearest first, each entry saying how far. -->
<maplace-map id="nearest-map" api-key="YOUR_KEY" list list-sort="distance" my-location>
  <maplace-location location-id="london" lat="51.5074" lng="-0.1278" title="London"></maplace-location>
  <maplace-location location-id="bristol" lat="51.4545" lng="-2.5879" title="Bristol"></maplace-location>
  <maplace-location location-id="birmingham" lat="52.4862" lng="-1.8904" title="Birmingham"></maplace-location>
  <maplace-location location-id="manchester" lat="53.4808" lng="-2.2426" title="Manchester"></maplace-location>
  <maplace-location location-id="leeds" lat="53.8008" lng="-1.5491" title="Leeds"></maplace-location>
</maplace-map>
```

### Script on MapLibre

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

```html
<!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, what the map and its list mount 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>
  #nearest-maplibre-script-map-and-list { display: flex; height: 24rem; }
  #nearest-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
  #nearest-maplibre-script-list { display: contents; }
  #nearest-maplibre-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #nearest-maplibre-script-map-and-list { flex-direction: column; }
    #nearest-maplibre-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="nearest-maplibre-script-map-and-list">
  <div id="nearest-maplibre-script-map"></div>
  <div id="nearest-maplibre-script-list"></div>
</div>
<script type="module">
  Maplace.createMapLibreMap("#nearest-maplibre-script-map", {
    locations: [
      { id: "london", lat: 51.5074, lng: -0.1278, title: "London" },
      { id: "bristol", lat: 51.4545, lng: -2.5879, title: "Bristol" },
      { id: "birmingham", lat: 52.4862, lng: -1.8904, title: "Birmingham" },
      { id: "manchester", lat: 53.4808, lng: -2.2426, title: "Manchester" },
      { id: "leeds", lat: 53.8008, lng: -1.5491, title: "Leeds" },
    ],
    list: { container: "#nearest-maplibre-script-list", sort: "distance" },
    myLocation: true,
  });
</script>
```

### Script on Google

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

```html
<!doctype html>
<!-- A page of your own script: the CDN script, what the map and its list mount 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>
  #nearest-script-map-and-list { display: flex; height: 24rem; }
  #nearest-script-map { flex: 1 1 auto; min-width: 0; }
  #nearest-script-list { display: contents; }
  #nearest-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #nearest-script-map-and-list { flex-direction: column; }
    #nearest-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="nearest-script-map-and-list">
  <div id="nearest-script-map"></div>
  <div id="nearest-script-list"></div>
</div>
<script type="module">
  Maplace.createGoogleMap("#nearest-script-map", {
    apiKey: "YOUR_KEY",
    locations: [
      { id: "london", lat: 51.5074, lng: -0.1278, title: "London" },
      { id: "bristol", lat: 51.4545, lng: -2.5879, title: "Bristol" },
      { id: "birmingham", lat: 52.4862, lng: -1.8904, title: "Birmingham" },
      { id: "manchester", lat: 53.4808, lng: -2.2426, title: "Manchester" },
      { id: "leeds", lat: 53.8008, lng: -1.5491, title: "Leeds" },
    ],
    list: { container: "#nearest-script-list", sort: "distance" },
    myLocation: true,
  });
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/nearest/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>
  #nearest-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
  #nearest-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #nearest-maplibre-vanilla-list { display: contents; }
  #nearest-maplibre-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #nearest-maplibre-vanilla-map-and-list { flex-direction: column; }
    #nearest-maplibre-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="nearest-maplibre-vanilla-map-and-list">
  <div id="nearest-maplibre-vanilla-map"></div>
  <div id="nearest-maplibre-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

createMapLibreMap("#nearest-maplibre-vanilla-map", {
  locations: [
    { id: "london", lat: 51.5074, lng: -0.1278, title: "London" },
    { id: "bristol", lat: 51.4545, lng: -2.5879, title: "Bristol" },
    { id: "birmingham", lat: 52.4862, lng: -1.8904, title: "Birmingham" },
    { id: "manchester", lat: 53.4808, lng: -2.2426, title: "Manchester" },
    { id: "leeds", lat: 53.8008, lng: -1.5491, title: "Leeds" },
  ],
  list: { container: "#nearest-maplibre-vanilla-list", sort: "distance" },
  myLocation: true,
});
```

### Bundler on Google

`packages/maplace/examples/nearest/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>
  #nearest-vanilla-map-and-list { display: flex; height: 24rem; }
  #nearest-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #nearest-vanilla-list { display: contents; }
  #nearest-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #nearest-vanilla-map-and-list { flex-direction: column; }
    #nearest-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="nearest-vanilla-map-and-list">
  <div id="nearest-vanilla-map"></div>
  <div id="nearest-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

createGoogleMap("#nearest-vanilla-map", {
  locations: [
    { id: "london", lat: 51.5074, lng: -0.1278, title: "London" },
    { id: "bristol", lat: 51.4545, lng: -2.5879, title: "Bristol" },
    { id: "birmingham", lat: 52.4862, lng: -1.8904, title: "Birmingham" },
    { id: "manchester", lat: 53.4808, lng: -2.2426, title: "Manchester" },
    { id: "leeds", lat: 53.8008, lng: -1.5491, title: "Leeds" },
  ],
  list: { container: "#nearest-vanilla-list", sort: "distance" },
  myLocation: true,
});
```

### React on MapLibre

`packages/maplace/examples/nearest/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>
  #nearest-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
  #nearest-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
  #nearest-maplibre-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #nearest-maplibre-react-root .map-and-list { flex-direction: column; }
    #nearest-maplibre-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="nearest-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/nearest/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, MyLocation } from "@maplacejs/maplace/react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

const cities: Location[] = [
  { id: "london", lat: 51.5074, lng: -0.1278, title: "London" },
  { id: "bristol", lat: 51.4545, lng: -2.5879, title: "Bristol" },
  { id: "birmingham", lat: 52.4862, lng: -1.8904, title: "Birmingham" },
  { id: "manchester", lat: 53.4808, lng: -2.2426, title: "Manchester" },
  { id: "leeds", lat: 53.8008, lng: -1.5491, title: "Leeds" },
];

function Nearest() {
  return (
    <MaplaceProvider locations={cities}>
      <div className="map-and-list">
        <MaplaceMap createAdapter={createMapLibreAdapter} className="map">
          <MyLocation />
        </MaplaceMap>
        <LocationList sort="distance" />
      </div>
    </MaplaceProvider>
  );
}

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

### React on Google

`packages/maplace/examples/nearest/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>
  #nearest-react-root .map-and-list { display: flex; height: 24rem; }
  #nearest-react-root .map { flex: 1 1 auto; min-width: 0; }
  #nearest-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #nearest-react-root .map-and-list { flex-direction: column; }
    #nearest-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="nearest-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

const cities: Location[] = [
  { id: "london", lat: 51.5074, lng: -0.1278, title: "London" },
  { id: "bristol", lat: 51.4545, lng: -2.5879, title: "Bristol" },
  { id: "birmingham", lat: 52.4862, lng: -1.8904, title: "Birmingham" },
  { id: "manchester", lat: 53.4808, lng: -2.2426, title: "Manchester" },
  { id: "leeds", lat: 53.8008, lng: -1.5491, title: "Leeds" },
];

function Nearest() {
  return (
    <MaplaceProvider locations={cities}>
      <div className="map-and-list">
        <MaplaceMap createAdapter={createGoogleAdapter} className="map">
          <MyLocation />
        </MaplaceMap>
        <LocationList sort="distance" />
      </div>
    </MaplaceProvider>
  );
}

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