# Click to add and drag markers

A click on the map adds a pin there, and every pin drags to a new place.

## How it works

A click on the map adds a pin where it landed, and every pin here can be dragged to a new place.

- **HTML**: `editable` on a `<maplace-location>` makes it draggable ([Location attributes](/element/#location-attributes)). A `maplace-mapclick` listener assigns the `locations` property, the current ones and the new pin ([Events](/element/#events)); assigning it, rather than adding a `<maplace-location>`, keeps a dragged pin where it is, as children are read again when they change. `center` and `zoom` on `<maplace-map>` set the first view ([Map attributes](/element/#map-attributes)).
- **Script** and **Bundler**: `editable: true` on a location ([Every location](/locations/#every-location)), and a `mapClick` listener calling `setLocations` with the snapshot's locations and the new pin ([Methods](/store/#methods), [Events](/store/#events)). `view` sets the first view, a centre and zoom ([The first view](/store/#the-first-view)).
- **React**: `onMapClick` adds the pin to your state, and `onLocationChange` writes a dragged one back there, or the next render would put it back ([Event props](/react/#event-props)). `view` on `<MaplaceProvider>` sets the same first view.

## Code

### HTML on MapLibre

`packages/maplace/examples/click-to-add/maplibre/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- A click on the map adds a pin there, and every pin drags: editable, written back to the store. -->
<maplace-map id="click-to-add-maplibre-map" center="44,11" zoom="6">
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome" editable></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan" editable></maplace-location>
</maplace-map>
<script>
  const clickToAddMapLibreMap = document.getElementById('click-to-add-maplibre-map');
  let clickToAddMapLibrePins = 0;
  clickToAddMapLibreMap.addEventListener('maplace-mapclick', (event) => {
    clickToAddMapLibrePins += 1;
    const pin = { id: `pin-${clickToAddMapLibrePins}`, ...event.detail.position, title: `Pin ${clickToAddMapLibrePins}`, editable: true };
    clickToAddMapLibreMap.locations = [...clickToAddMapLibreMap.locations, pin];
  });
</script>
```

### HTML on Google

`packages/maplace/examples/click-to-add/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- A click on the map adds a pin there, and every pin drags: editable, written back to the store. -->
<maplace-map id="click-to-add-map" api-key="YOUR_KEY" center="44,11" zoom="6">
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome" editable></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan" editable></maplace-location>
</maplace-map>
<script>
  const clickToAddMap = document.getElementById('click-to-add-map');
  let clickToAddPins = 0;
  clickToAddMap.addEventListener('maplace-mapclick', (event) => {
    clickToAddPins += 1;
    const pin = { id: `pin-${clickToAddPins}`, ...event.detail.position, title: `Pin ${clickToAddPins}`, editable: true };
    clickToAddMap.locations = [...clickToAddMap.locations, pin];
  });
</script>
```

### Script on MapLibre

`packages/maplace/examples/click-to-add/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 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>
  #click-to-add-maplibre-script-map { height: 24rem; }
</style>
<div id="click-to-add-maplibre-script-map"></div>
<script type="module">
  const maplace = Maplace.createMapLibreMap("#click-to-add-maplibre-script-map", {
    locations: [
      { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", editable: true },
      { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", editable: true },
    ],
    view: { kind: "center", center: { lat: 44, lng: 11 }, zoom: 6 },
  });

  let pins = 0;
  maplace.on("mapClick", ({ position }) => {
    pins += 1;
    const pin = { id: `pin-${pins}`, ...position, title: `Pin ${pins}`, editable: true };
    maplace.setLocations([...maplace.getSnapshot().locations, pin]);
  });
</script>
```

### Script on Google

`packages/maplace/examples/click-to-add/script.html`

```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>
  #click-to-add-script-map { height: 24rem; }
</style>
<div id="click-to-add-script-map"></div>
<script type="module">
  const maplace = Maplace.createGoogleMap("#click-to-add-script-map", {
    apiKey: "YOUR_KEY",
    locations: [
      { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", editable: true },
      { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", editable: true },
    ],
    view: { kind: "center", center: { lat: 44, lng: 11 }, zoom: 6 },
  });

  let pins = 0;
  maplace.on("mapClick", ({ position }) => {
    pins += 1;
    const pin = { id: `pin-${pins}`, ...position, title: `Pin ${pins}`, editable: true };
    maplace.setLocations([...maplace.getSnapshot().locations, pin]);
  });
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/click-to-add/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>
  #click-to-add-maplibre-vanilla-map { height: 24rem; }
</style>
<div id="click-to-add-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/click-to-add/maplibre/vanilla.ts`

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

const maplace = createMapLibreMap("#click-to-add-maplibre-vanilla-map", {
  locations: [
    { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", editable: true },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", editable: true },
  ],
  view: { kind: "center", center: { lat: 44, lng: 11 }, zoom: 6 },
});

let pins = 0;
maplace.on("mapClick", ({ position }) => {
  pins += 1;
  const pin = { id: `pin-${pins}`, ...position, title: `Pin ${pins}`, editable: true };
  maplace.setLocations([...maplace.getSnapshot().locations, pin]);
});
```

### Bundler on Google

`packages/maplace/examples/click-to-add/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>
  #click-to-add-vanilla-map { height: 24rem; }
</style>
<div id="click-to-add-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/click-to-add/vanilla.ts`

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

const maplace = createGoogleMap("#click-to-add-vanilla-map", {
  locations: [
    { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", editable: true },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", editable: true },
  ],
  view: { kind: "center", center: { lat: 44, lng: 11 }, zoom: 6 },
});

let pins = 0;
maplace.on("mapClick", ({ position }) => {
  pins += 1;
  const pin = { id: `pin-${pins}`, ...position, title: `Pin ${pins}`, editable: true };
  maplace.setLocations([...maplace.getSnapshot().locations, pin]);
});
```

### React on MapLibre

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

`packages/maplace/examples/click-to-add/maplibre/react.tsx`

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

const cities: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", editable: true },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", editable: true },
];

const firstView: View = { kind: "center", center: { lat: 44, lng: 11 }, zoom: 6 };

/** The pin a click on the map adds, the `count`th. */
function addedPin(position: LatLng, count: number): Location {
  return { id: `pin-${count}`, ...position, title: `Pin ${count}`, editable: true };
}

function ClickToAdd() {
  const [locations, setLocations] = useState(cities);
  const addPin = ({ position }: { readonly position: LatLng }) =>
    setLocations((current) => [...current, addedPin(position, current.length - cities.length + 1)]);
  // The store has the dragged place already: kept here too, or the next pin would put it back.
  const keepMoved = ({ location }: { readonly location: Location }) =>
    setLocations((current) =>
      current.map((other) => (other.id === location.id ? location : other)),
    );
  return (
    <MaplaceProvider
      view={firstView}
      locations={locations}
      onMapClick={addPin}
      onLocationChange={keepMoved}
    >
      <MaplaceMap createAdapter={createMapLibreAdapter} className="map" />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("click-to-add-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <ClickToAdd />
  </StrictMode>,
);
```

### React on Google

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

`packages/maplace/examples/click-to-add/react.tsx`

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

const cities: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome", editable: true },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan", editable: true },
];

const firstView: View = { kind: "center", center: { lat: 44, lng: 11 }, zoom: 6 };

/** The pin a click on the map adds, the `count`th. */
function addedPin(position: LatLng, count: number): Location {
  return { id: `pin-${count}`, ...position, title: `Pin ${count}`, editable: true };
}

function ClickToAdd() {
  const [locations, setLocations] = useState(cities);
  const addPin = ({ position }: { readonly position: LatLng }) =>
    setLocations((current) => [...current, addedPin(position, current.length - cities.length + 1)]);
  // The store has the dragged place already: kept here too, or the next pin would put it back.
  const keepMoved = ({ location }: { readonly location: Location }) =>
    setLocations((current) =>
      current.map((other) => (other.id === location.id ? location : other)),
    );
  return (
    <MaplaceProvider
      view={firstView}
      locations={locations}
      onMapClick={addPin}
      onLocationChange={keepMoved}
    >
      <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("click-to-add-react-root") as HTMLElement).render(
  <StrictMode>
    <ClickToAdd />
  </StrictMode>,
);
```
