Maplace.js

Markers and popups

Click to add and drag markers

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

Markdown

Map and code

Run the examples on

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>

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). A maplace-mapclick listener assigns the locations property, 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. center and zoom on <maplace-map> set the first view (Map attributes).
  • Script and Bundler: editable: true on a location (Every location), and a mapClick listener calling setLocations with the snapshot’s locations and the new pin (Methods, Events). view sets the first view, a centre and zoom (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). view on <MaplaceProvider> sets the same first view.