Working with HTMX
To add HTMX to a project. Add a script tag to pull the library into your page.
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
<!-- have a button POST a click via AJAX -->
<button hx-get="/clicked" hx-swap="outerHTML">
Click Me
</button>
Use with Leaflet-HTML
The principles that govern HTMX development also hold for Leaflet-HTML. A button that requests HTML to replace part of the document should update the map.
<!-- Initial map -->
<l-map center="[55,-5]" zoom="4">
<l-tile-layer
url-template="https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png"
></l-tile-layer>
</l-map>
<!-- Tiles -->
<button hx-get="/tile-osm.html" hx-target="l-tile-layer" hx-swap="outerHTML">
OSM
</button>
<button hx-get="/tile-voyager.html" hx-target="l-tile-layer" hx-swap="outerHTML">
Voyager
</button>
<button hx-get="/tile-esri.html" hx-target="l-tile-layer" hx-swap="outerHTML">
ESRI
</button>
<!-- Marker -->
<button hx-get="/marker.html" hx-target="l-map" hx-swap="beforeend">
Add marker
</button>
<button hx-get="/marker.html" hx-target="l-marker" hx-swap="delete">
Delete marker
</button>
The above approach works by triggering the change handlers in the <l-tile-layer>
custom element.
The additional HTML tags generated by Leaflet are also inside the <l-map>
tag.
Care should be taken to not hx-swap
the tags governed by Leaflet.
All Leaflet-HTML tags, e.g. <l-marker>
, <l-icon>
, etc. can be swapped however you like.
It is just the contents of <l-map>
that needs careful consideration.
A more elegant mechanism in the future will make it clear which part of the document is controlled by Leaflet.
Marker as a hypermedia control
<l-marker
lat-lng="[55,-5]"
on="click"
hx-trigger="click"
hx-target="#placeholder"
hx-get="/clicked"></l-marker>
<div id="placeholder">Hello, World!</div>
Hello, World!
When the marker is clicked HTMX replaces the content of the above heading.
Leaflet-HTML connects Leaflet's event system to browser native DOM events. HTMX uses browser DOM events to orchestrate network requests and DOM updates.