from fasthtml.common import * leaflet_css = Link(rel="stylesheet", href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css", type='text/css') leaflet_js = Script(src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js") app, rt = fast_app(hdrs=(leaflet_css, leaflet_js), live=True) @dataclass class Coords: latitude:str longitude:str leaflet_init = Script(""" var map = L.map("map").setView([51.505, -0.09], 13); L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", { attribution: '© OpenStreetMap contributors', }).addTo(map); // Bubble up a custom event with the latitude and longitude map.on("click", function (e) { console.log(e); htmx.ajax("POST", "/map-click", { target: "#info-panel", values: { latitude: e.latlng.lat, longitude: e.latlng.lng, }, }); }); """) map = Div(id="map", hx_trigger="leaflet-click from:document", hx_get="/map-click", hx_target="#info-panel", style="height: 400px;") info_panel = Div(id="info-panel") @app.get("/") def home(): return ( Title("Map"), Main( H1("Leaflet in FastHTML"), map, info_panel, leaflet_init, cls="container", ), ) @app.post("/map-click") def map_click(coords: Coords): return P(f"Clicked at: {coords.latitude}, {coords.longitude}") serve()