Created
September 15, 2024 18:45
-
-
Save andfanilo/62ccf252aa5e9f90f61259bf4b9d11c1 to your computer and use it in GitHub Desktop.
Discovering FastHTML with Leaflet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fasthtml.common import * | |
leaflet_css = Link(rel="stylesheet", href="https://unpkg.com/[email protected]/dist/leaflet.css", type='text/css') | |
leaflet_js = Script(src="https://unpkg.com/[email protected]/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: | |
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment