Click to add and drag markers
A click on the map adds a pin there, and every pin drags to a new place.
Map and code
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
These maps come from Google Maps and OpenFreeMap, which see your IP address. They stay off until you say so, once for the whole site. What loading the maps sends
<!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><!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><!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><!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><!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>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]);
});<!doctype html>
<!-- The page vanilla.ts runs on: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->Google's bootstrap loader, with your API key: from Google's docs
<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>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]);
});<!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>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>,
);<!doctype html>
<!-- The page react.tsx renders into: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->Google's bootstrap loader, with your API key: from Google's docs
<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>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>,
);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:
editableon a<maplace-location>makes it draggable (Location attributes). Amaplace-mapclicklistener assigns thelocationsproperty, the current ones and the new pin (Events); assigning it, rather than adding a<maplace-location>, keeps a dragged pin where it is, as children are read again when they change.centerandzoomon<maplace-map>set the first view (Map attributes). - Script and Bundler:
editable: trueon a location (Every location), and amapClicklistener callingsetLocationswith the snapshot’s locations and the new pin (Methods, Events).viewsets the first view, a centre and zoom (The first view). - React:
onMapClickadds the pin to your state, andonLocationChangewrites a dragged one back there, or the next render would put it back (Event props).viewon<MaplaceProvider>sets the same first view.