Files
roman-time/index.html
T

1051 lines
53 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="description" content="What hour is it in ancient Rome? A live digital sundial for wherever you are.">
<meta name="theme-color" content="#f4ece0" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#14110d" media="(prefers-color-scheme: dark)">
<title>Roman Time</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cpath d='M2 26a14 14 0 0 1 28 0z' fill='%23c2410c'/%3E%3Cpath d='M16 26 6 15' stroke='%23fff' stroke-width='2.5' stroke-linecap='round'/%3E%3C/svg%3E">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@500;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<style>
:root {
--bg: #f4ece0;
--bg-glow: #fbd9a8;
--surface: #fffaf2;
--surface-2: #efe4d3;
--border: #e2d4bf;
--text: #2a2118;
--muted: #7a6a58;
--accent: #c2410c;
--accent-soft: #f6c99a;
--stone: #e6dac6;
--stone-top: #f4ecdf;
--stone-dark: #cbb898;
--bowl-rim: #c9b899;
--bowl-deep: #f3ebde;
--dial-line: #9c8566;
--band: rgba(194, 65, 12, .22);
--band-done: rgba(122, 106, 88, .10);
--shadow-hand: rgba(42, 33, 24, .6);
--bronze: #a8773a;
--bronze-dark: #6f4c22;
--water: #4f8fd6;
--star: transparent;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14110d;
--bg-glow: #4a2a12;
--surface: #1f1a14;
--surface-2: #2a231b;
--border: #3a3026;
--text: #f3e9da;
--muted: #a8977f;
--accent: #f59e0b;
--accent-soft: #7c4a14;
--stone: #4a4034;
--stone-top: #5b5043;
--stone-dark: #352d24;
--bowl-rim: #2c251d;
--bowl-deep: #5a4e40;
--dial-line: #a08a6c;
--band: rgba(245, 158, 11, .25);
--band-done: rgba(0, 0, 0, .12);
--shadow-hand: rgba(0, 0, 0, .75);
}
}
body.night {
--bg: #0b1020;
--bg-glow: #1e2a5a;
--surface: #131a30;
--surface-2: #1b2442;
--border: #27325a;
--text: #e6eaf7;
--muted: #8f9bc2;
--accent: #a5b4fc;
--accent-soft: #3b4785;
--stone: #323c62;
--stone-top: #3d4874;
--stone-dark: #232b4b;
--bowl-rim: #1b2240;
--bowl-deep: #3a4570;
--dial-line: #7d8bc4;
--band: rgba(165, 180, 252, .28);
--band-done: rgba(0, 0, 0, .15);
--shadow-hand: rgba(0, 0, 0, .6);
--bronze: #b98d4e;
--bronze-dark: #7a5728;
--water: #6ea8ff;
--star: #c7d2fe;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0;
min-height: 100vh;
min-height: 100dvh;
font-family: Inter, system-ui, -apple-system, sans-serif;
color: var(--text);
background: var(--bg);
background-image: radial-gradient(120% 60% at 50% 0%, var(--bg-glow) 0%, transparent 60%);
background-attachment: fixed;
transition: background-color .8s, color .8s;
-webkit-font-smoothing: antialiased;
}
.app {
max-width: 560px;
margin: 0 auto;
padding: max(16px, env(safe-area-inset-top)) 16px max(32px, env(safe-area-inset-bottom));
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.brand {
font-family: Cinzel, serif;
font-weight: 700;
letter-spacing: .14em;
font-size: 15px;
}
.loc-btn {
display: inline-flex;
align-items: center;
gap: 6px;
max-width: 60%;
padding: 8px 12px;
border-radius: 999px;
border: 1px solid var(--border);
background: var(--surface);
color: var(--text);
font: inherit;
font-size: 13px;
cursor: pointer;
}
.loc-btn span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.loc-btn svg { flex: none; color: var(--accent); }
.dial-wrap { position: relative; margin: 8px -8px 0; }
.dial-wrap svg { display: block; width: 100%; height: auto; }
.dial-wrap svg[hidden] { display: none; }
.stone { fill: var(--stone); }
.stone-top { fill: var(--stone-top); }
.stone-dark { fill: var(--stone-dark); }
.g-rim { stop-color: var(--bowl-rim); }
.g-deep { stop-color: var(--bowl-deep); }
.band { fill: transparent; transition: fill .4s; }
.band.done { fill: var(--band-done); }
.band.now { fill: var(--band); }
.hour-line { stroke: var(--dial-line); stroke-width: 1; fill: none; }
.day-curve { stroke: var(--dial-line); stroke-width: 1.6; fill: none; transition: stroke .2s, stroke-width .2s; }
.today { stroke: var(--accent); stroke-width: 1.2; stroke-dasharray: 4 3; fill: none; opacity: .85; transition: stroke-width .2s; }
.day-curve.active { stroke: var(--accent); stroke-width: 3; }
.today.active { stroke-width: 3; opacity: 1; }
.hit { stroke: transparent; stroke-width: 16; fill: none; pointer-events: stroke; cursor: pointer; -webkit-tap-highlight-color: transparent; }
.hit:focus { outline: none; }
.horizon-line { stroke: var(--dial-line); stroke-width: 1; opacity: .6; }
.curve-info { min-height: 2.6em; margin: 2px 8px 0; text-align: center; font-size: 13px; line-height: 1.35; color: var(--muted); }
.curve-info b { color: var(--text); font-weight: 600; }
.drum-shade { pointer-events: none; }
.month-line { stroke: var(--dial-line); stroke-width: .6; opacity: .5; }
.month-label { font-family: Cinzel, serif; font-size: 7px; fill: var(--muted); text-anchor: middle; dominant-baseline: central; }
.drop { fill: var(--water); }
.ripple { fill: none; stroke: var(--water); stroke-width: 1; }
.numeral { font-family: Cinzel, serif; font-size: 12px; font-weight: 500; fill: var(--muted); text-anchor: middle; dominant-baseline: central; }
.numeral.now { fill: var(--accent); font-weight: 700; }
.shadow { fill: var(--shadow-hand); filter: url(#soft); }
.tip { fill: var(--accent); }
.bronze { fill: var(--bronze); }
.bronze-dark { fill: var(--bronze-dark); }
.bronze-line { stroke: var(--bronze); fill: none; }
.water { fill: var(--water); opacity: .7; }
.vessel { fill: var(--bg); opacity: .55; }
.stream { stroke: var(--water); stroke-width: 2; stroke-dasharray: 4 4; }
.col-line { stroke: var(--dial-line); stroke-width: 1; }
.col-line.vigil { stroke-width: 2; }
.star { fill: var(--star); }
.readout { text-align: center; margin-top: 4px; }
.numeral-big {
font-family: Cinzel, serif;
font-weight: 700;
font-size: clamp(64px, 22vw, 104px);
line-height: 1;
letter-spacing: .04em;
color: var(--accent);
}
.latin {
font-family: Cinzel, serif;
font-size: 20px;
letter-spacing: .08em;
margin-top: 6px;
}
.phrase { color: var(--muted); margin-top: 6px; font-size: 15px; }
.progress {
margin: 20px 0 0;
padding: 14px 16px;
border-radius: 16px;
background: var(--surface);
border: 1px solid var(--border);
}
.progress-row { display: flex; justify-content: space-between; gap: 12px; font-size: 13px; color: var(--muted); }
.progress-row b { color: var(--text); font-weight: 600; }
.bar { height: 6px; border-radius: 3px; background: var(--surface-2); margin-top: 10px; overflow: hidden; }
.bar i { display: block; height: 100%; width: 0; background: var(--accent); border-radius: 3px; transition: width 1s linear; }
.stats {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
margin-top: 10px;
}
.stat {
padding: 12px 14px;
border-radius: 14px;
background: var(--surface);
border: 1px solid var(--border);
}
.stat small { display: block; font-size: 12px; color: var(--muted); }
.stat strong { display: block; font-size: 18px; font-weight: 600; margin-top: 2px; font-variant-numeric: tabular-nums; }
.scrub {
margin-top: 10px;
padding: 12px 16px;
border-radius: 16px;
background: var(--surface);
border: 1px solid var(--border);
}
.scrub-head { display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: var(--muted); }
.scrub-head b { color: var(--text); font-weight: 600; font-variant-numeric: tabular-nums; }
.link-btn { background: none; border: 0; color: var(--accent); font: inherit; font-size: 13px; font-weight: 600; cursor: pointer; padding: 4px 0; }
.link-btn[hidden] { display: none; }
input[type=range] { width: 100%; margin: 10px 0 2px; accent-color: var(--accent); }
h2 {
font-family: Cinzel, serif;
font-size: 14px;
letter-spacing: .12em;
color: var(--muted);
margin: 28px 4px 10px;
font-weight: 700;
}
.hours {
list-style: none;
margin: 0;
padding: 0;
border-radius: 16px;
overflow: hidden;
border: 1px solid var(--border);
background: var(--surface);
}
.hours li {
display: grid;
grid-template-columns: 52px 1fr auto;
align-items: center;
gap: 8px;
padding: 11px 16px;
border-top: 1px solid var(--border);
font-size: 14px;
}
.hours li:first-child { border-top: 0; }
.hours .n { font-family: Cinzel, serif; font-weight: 700; color: var(--muted); }
.hours .t { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 13px; }
.hours li.past { opacity: .5; }
.hours li.now { background: var(--accent-soft); }
.hours li.now .n { color: var(--accent); }
body.night .hours li.now .n { color: var(--text); }
.about { color: var(--muted); font-size: 14px; line-height: 1.6; margin: 0 4px; }
.about a, .sources a { color: var(--accent); }
.about + .about { margin-top: 12px; }
.sources { color: var(--muted); font-size: 13px; line-height: 1.55; margin: 0 4px; padding-left: 18px; }
.sources li + li { margin-top: 8px; }
footer { text-align: center; font-size: 12px; color: var(--muted); margin-top: 28px; }
/* location sheet */
dialog {
width: min(560px, 100%);
max-width: 100%;
max-height: 92dvh;
margin: auto auto 0;
padding: 20px 16px max(20px, env(safe-area-inset-bottom));
border: 0;
border-radius: 20px 20px 0 0;
background: var(--surface);
color: var(--text);
}
@media (min-width: 600px) {
dialog { margin: auto; border-radius: 20px; }
}
dialog::backdrop { background: rgba(0, 0, 0, .45); }
.sheet-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.sheet-head h3 { margin: 0; font-family: Cinzel, serif; letter-spacing: .08em; font-size: 17px; }
.primary {
width: 100%;
padding: 13px;
border: 0;
border-radius: 12px;
background: var(--accent);
color: #fff;
font: inherit;
font-weight: 600;
cursor: pointer;
}
body.night .primary { color: #0b1020; }
#map {
height: 260px;
border-radius: 14px;
margin: 12px 0;
border: 1px solid var(--border);
z-index: 0;
}
.coords { display: grid; grid-template-columns: 1fr 1fr auto; gap: 8px; }
.coords label { font-size: 12px; color: var(--muted); }
.coords input {
display: block;
width: 100%;
margin-top: 4px;
padding: 10px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--bg);
color: var(--text);
font: inherit;
font-size: 16px;
}
.coords button {
align-self: end;
padding: 10px 14px;
border-radius: 10px;
border: 1px solid var(--border);
background: var(--surface-2);
color: var(--text);
font: inherit;
font-weight: 600;
cursor: pointer;
}
.tz-note { font-size: 12px; color: var(--muted); text-align: center; margin: 10px 0 0; }
.hours small { font-size: 11px; color: var(--muted); margin-left: 6px; letter-spacing: .02em; }
.hint { font-size: 12px; color: var(--muted); margin: 8px 0 0; min-height: 1em; }
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">ROMAN TIME</div>
<button class="loc-btn" id="openLoc" type="button" aria-label="Change location">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 2a7 7 0 0 0-7 7c0 5.25 7 13 7 13s7-7.75 7-13a7 7 0 0 0-7-7zm0 9.5A2.5 2.5 0 1 1 12 6.5a2.5 2.5 0 0 1 0 5z"/></svg>
<span id="locLabel">Locating…</span>
</button>
</header>
<div class="dial-wrap">
<svg id="sundial" viewBox="0 0 400 268" role="img" aria-labelledby="dialTitle">
<title id="dialTitle">Hemicyclium sundial</title>
<defs>
<filter id="soft" x="-20%" y="-20%" width="140%" height="140%">
<feGaussianBlur stdDeviation="1.2"/>
</filter>
<radialGradient id="bowlGrad" cx="200" cy="200" r="230" gradientUnits="userSpaceOnUse">
<stop offset="0" class="g-deep"/>
<stop offset="1" class="g-rim"/>
</radialGradient>
</defs>
<!-- Berosus' hemicyclium: "the semicircle, hollowed in a square, and inclined according to the climate" (Vitruvius IX.8.1) -->
<path class="stone-top" d="M 14 52 L 40 22 H 360 L 386 52 Z"/>
<rect class="stone" x="14" y="52" width="372" height="196"/>
<rect class="stone-dark" x="6" y="246" width="388" height="16" rx="2"/>
<path class="bowl" fill="url(#bowlGrad)" d="M 30 52 A 170 170 0 0 0 370 52 Z"/>
<g id="bands"></g>
<g id="dialLines"></g>
<path id="todayCurve" class="today"/>
<g id="numerals"></g>
<path id="shadow" class="shadow"/>
<circle id="tip" class="tip" r="3.5" cx="200" cy="52"/>
<!-- gnomon: its base sits where the shadow begins -->
<path class="bronze" d="M 197 52 L 203 52 L 201.5 74 L 198.5 74 Z"/>
<circle class="bronze-dark" cx="200" cy="74" r="2.5"/>
<g id="hits"></g>
</svg>
<svg id="clepsydra" viewBox="0 0 400 400" role="img" aria-label="Water clock of Ctesibius" hidden>
<defs>
<linearGradient id="drumShade" x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stop-color="#000" stop-opacity=".45"/>
<stop offset=".35" stop-color="#000" stop-opacity="0"/>
<stop offset=".5" stop-color="#fff" stop-opacity=".06"/>
<stop offset=".65" stop-color="#000" stop-opacity="0"/>
<stop offset="1" stop-color="#000" stop-opacity=".45"/>
</linearGradient>
</defs>
<g id="stars"></g>
<!-- supply pipe and constant-head tank -->
<path class="bronze-line" stroke-width="5" d="M 64 0 V 104"/>
<line class="stream" x1="64" y1="106" x2="64" y2="134"/>
<rect class="vessel" x="24" y="118" width="84" height="58" rx="3"/>
<rect class="water" x="24" y="132" width="84" height="44"/>
<path class="bronze-line" stroke-width="4" d="M 24 118 V 176 H 108 V 118"/>
<path class="bronze-line" stroke-width="4" d="M 24 132 H 8 V 160"/>
<line class="stream" x1="8" y1="162" x2="8" y2="250"/>
<!-- orifice and feed to the cylinder -->
<path class="bronze-line" stroke-width="4" d="M 92 176 V 192 H 126 V 204"/>
<!-- receiving cylinder -->
<rect class="vessel" x="118" y="230" width="84" height="160" rx="3"/>
<rect id="water" class="water" x="118" y="380" width="84" height="10"/>
<g id="drops"></g>
<path class="bronze-line" stroke-width="4" d="M 118 230 V 392 H 202 V 230"/>
<path class="bronze-line" stroke-width="3" d="M 112 230 H 120 M 132 230 H 152 M 168 230 H 208"/>
<!-- rotating drum of hours, turned so today's date faces the pointer -->
<rect class="stone-dark" x="252" y="32" width="64" height="12" rx="2"/>
<rect class="stone" x="260" y="44" width="48" height="178"/>
<g id="column"></g>
<rect class="drum-shade" fill="url(#drumShade)" x="260" y="44" width="48" height="178"/>
<rect class="stone-dark" x="252" y="220" width="64" height="12" rx="2"/>
<rect class="stone" x="246" y="232" width="76" height="150"/>
<rect class="stone-dark" x="240" y="380" width="88" height="12" rx="2"/>
<!-- float, rod and figure ride the water -->
<g id="float">
<rect class="bronze-dark" x="134" y="370" width="62" height="10" rx="3"/>
<rect class="bronze" x="158.5" y="214" width="3" height="156"/>
<circle class="bronze" cx="160" cy="184" r="6"/>
<path class="bronze" d="M 154 214 L 156 192 H 164 L 166 214 Z"/>
<path class="bronze-line" stroke-width="2" d="M 162 198 L 284 200"/>
<circle class="tip" cx="284" cy="200" r="2.5"/>
</g>
</svg>
</div>
<p class="curve-info" id="curveInfo"></p>
<div class="readout" aria-live="polite">
<div class="numeral-big" id="bigNumeral">–</div>
<div class="latin" id="latin">&nbsp;</div>
<div class="phrase" id="phrase">&nbsp;</div>
</div>
<div class="progress">
<div class="progress-row"><span id="progLeft">&nbsp;</span><span id="progRight">&nbsp;</span></div>
<div class="bar"><i id="progBar"></i></div>
</div>
<div class="stats">
<div class="stat"><small id="s1l">Sunrise</small><strong id="s1">–</strong></div>
<div class="stat"><small id="s2l">Sunset</small><strong id="s2">–</strong></div>
<div class="stat"><small id="s3l">One Roman hour</small><strong id="s3">–</strong></div>
<div class="stat"><small id="s4l">Daylight</small><strong id="s4">–</strong></div>
</div>
<p class="tz-note" id="tzNote"></p>
<div class="scrub">
<div class="scrub-head">
<span>Preview time · <b id="scrubLabel">Now</b></span>
<button class="link-btn" id="scrubReset" type="button" hidden>Back to now</button>
</div>
<input type="range" id="scrub" min="-720" max="720" step="5" value="0" aria-label="Preview another time">
</div>
<h2 id="listTitle">Horae Diei</h2>
<ol class="hours" id="hourList"></ol>
<h2>About</h2>
<p class="about">
Romans split the daylight, from sunrise to sunset, into twelve equal
<a href="https://penelope.uchicago.edu/Thayer/E/Roman/Texts/secondary/SMIGRA*/Hora.html">horae</a>,
and the night into twelve more, grouped into four watches (<i>vigiliae</i>). So an hour stretched in
summer and shrank in winter.
</p>
<p class="about">
By day this page draws a <i>hemicyclium</i>, the hollow cut into a squared stone block that Vitruvius
credits to Berosus the Chaldean, laid out for your latitude. The gnomon's tip sits at the centre of the
sphere the hollow is cut from, so its shadow falls opposite the sun: it starts high on the west side at
sunrise, sinks to the bottom at noon and climbs to the east side by sunset. Eleven hour lines cross three
curves, as on surviving dials: the winter solstice (<i>bruma</i>), the equinox (<i>aequinoctium</i>) and
the summer solstice (<i>solstitium</i>). The dashed line is today's path.
</p>
<p class="about">
By night, when a sundial is useless, the page switches to the water clock of Ctesibius. Water drips at a
steady rate through a hole bored in gold or a gem into a cylinder, and a float lifts a figure whose wand
points to the hour on a column. Nights lengthen and shorten through the year, so Vitruvius marks
"the lines of the months" on the column and has it turn, giving the helical hour lines on the drum.
</p>
<h2>Sources</h2>
<ul class="sources">
<li>
<a href="https://penelope.uchicago.edu/Thayer/E/Roman/Texts/Vitruvius/9*.html">Vitruvius, <i>De Architectura</i>, Book IX</a>
(Gwilt translation, LacusCurtius). Chapter 8 covers Berosus' hemicyclium and Ctesibius' water clock: the gold or gem
orifice, the float, the figure with its wand and the turning column. Also in the
<a href="http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.02.0073:book=9:chapter=8">Morgan translation</a> (Perseus).
</li>
<li>
<a href="https://penelope.uchicago.edu/Thayer/E/Roman/Texts/secondary/SMIGRA*/Horologium.html">"Horologium"</a>
in Smith's <i>Dictionary of Greek and Roman Antiquities</i> (1875). Describes a hemicyclium found at Tusculum,
with eleven hour lines crossing three seasonal curves, and Ctesibius' clock.
</li>
<li>
<a href="https://penelope.uchicago.edu/Thayer/E/Roman/Texts/secondary/SMIGRA*/Hora.html">"Hora"</a>
in the same dictionary, on the twelve hours of the day and night.
</li>
<li>
<a href="http://www.perseus.tufts.edu/hopper/text?doc=Perseus:text:1999.02.0137:book=7:chapter=60">Pliny the Elder, <i>Natural History</i> VII.60</a>
(Perseus). Rome's first sundials and water clocks, including the dial brought from Catania that told the wrong time for 99 years.
</li>
<li>
<a href="https://archive.org/details/greekromansundia0000gibb_n3g4">Sharon L. Gibbs, <i>Greek and Roman Sundials</i></a>
(Yale, 1976). The standard catalogue of surviving dials and their geometry.
</li>
<li>
<a href="https://en.wikipedia.org/wiki/Roman_timekeeping">Roman timekeeping</a> (Wikipedia). An overview, including the night watches.
</li>
<li>
Sunrise and sunset are calculated with the formulas behind <a href="https://github.com/mourner/suncalc">SunCalc</a>,
after the <a href="https://gml.noaa.gov/grad/solcalc/">NOAA Solar Calculator</a>.
</li>
</ul>
<footer>romanti.me</footer>
</div>
<dialog id="locSheet">
<div class="sheet-head">
<h3>Location</h3>
<button class="link-btn" id="closeLoc" type="button">Done</button>
</div>
<button class="primary" id="useGps" type="button">Use my current location</button>
<div id="map"></div>
<form class="coords" id="coordForm">
<label>Latitude<input id="lat" inputmode="decimal" autocomplete="off" required></label>
<label>Longitude<input id="long" inputmode="decimal" autocomplete="off" required></label>
<button type="submit">Set</button>
</form>
<p class="hint" id="hint">Tap the map to pick a spot.</p>
</dialog>
<script>
if (
location.protocol != 'https:'
&& location.protocol != 'file:'
&& location.hostname != 'localhost'
) {
location.href = location.href.replace("http://", "https://");
}
const $ = id => document.getElementById(id);
// ---- solar math (after SunCalc / NOAA) ----
const rad = Math.PI / 180, dayMs = 864e5, J1970 = 2440588, J2000 = 2451545, J0 = 0.0009;
const obliquity = rad * 23.4397;
const toDays = date => date.valueOf() / dayMs - 0.5 + J1970 - J2000;
const fromJulian = j => new Date((j + 0.5 - J1970) * dayMs);
function sunTimes(date, lat, lng) {
const lw = rad * -lng, phi = rad * lat;
const n = Math.round(toDays(date) - J0 - lw / (2 * Math.PI));
const ds = J0 + lw / (2 * Math.PI) + n;
const M = rad * (357.5291 + 0.98560028 * ds);
const C = rad * (1.9148 * Math.sin(M) + 0.02 * Math.sin(2 * M) + 0.0003 * Math.sin(3 * M));
const L = M + C + rad * 102.9372 + Math.PI;
const dec = Math.asin(Math.sin(obliquity) * Math.sin(L));
const transit = j => J2000 + j + 0.0053 * Math.sin(M) - 0.0069 * Math.sin(2 * L);
const noon = transit(ds);
const cosH = (Math.sin(-0.833 * rad) - Math.sin(phi) * Math.sin(dec)) / (Math.cos(phi) * Math.cos(dec));
if (cosH > 1) return { polar: 'night' };
if (cosH < -1) return { polar: 'day' };
const set = transit(J0 + (Math.acos(cosH) + lw) / (2 * Math.PI) + n);
return { rise: fromJulian(noon - (set - noon)), set: fromJulian(set) };
}
// Find the daylight or night period containing time t.
function periodAt(t, lat, lng) {
const events = [];
for (let k = -2; k <= 2; k++) {
const s = sunTimes(new Date(t.getTime() + k * dayMs), lat, lng);
if (s.polar) continue;
events.push({ t: s.rise, type: 'rise' }, { t: s.set, type: 'set' });
}
events.sort((a, b) => a.t - b.t);
const uniq = events.filter((e, i) => i === 0 || Math.abs(e.t - events[i - 1].t) > 6e4);
for (let i = 0; i < uniq.length - 1; i++) {
const a = uniq[i], b = uniq[i + 1];
if (a.t <= t && t < b.t && a.type !== b.type) {
return { isDay: a.type === 'rise', start: a.t, end: b.t };
}
}
const s = sunTimes(t, lat, lng);
return { polar: s.polar || 'night' };
}
// ---- Roman bits ----
const NUMERALS = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"];
const ORDINALS = ["Prima", "Secunda", "Tertia", "Quarta", "Quinta", "Sexta", "Septima", "Octava", "Nona", "Decima", "Undecima", "Duodecima"];
const ENGLISH = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth"];
const VIGILIAE = ["Prima", "Secunda", "Tertia", "Quarta"];
function solarDec(date) {
const d = toDays(date);
const M = rad * (357.5291 + 0.98560028 * d);
const C = rad * (1.9148 * Math.sin(M) + 0.02 * Math.sin(2 * M) + 0.0003 * Math.sin(3 * M));
return Math.asin(Math.sin(obliquity) * Math.sin(M + C + rad * 102.9372 + Math.PI));
}
// ---- spherical sundial ----
// Front view of an equator-facing hollow sphere. The gnomon tip sits at the centre, so the shadow
// of the tip lands diametrically opposite the sun. Everything works in a "dial frame": latitude is
// taken as |lat| and, south of the equator, declination and east-west are mirrored so the dial faces north.
const svgNS = "http://www.w3.org/2000/svg";
const CX = 200, CY = 52, R = 170, SOLSTICE = 23.44 * rad, REFRACTION = -0.833 * rad;
const el = (tag, attrs, parent) => {
const e = document.createElementNS(svgNS, tag);
for (const k in attrs) e.setAttribute(k, attrs[k]);
parent.appendChild(e);
return e;
};
const clamp1 = v => Math.max(-1, Math.min(1, v));
const halfDayAngle = (phi, d) => Math.acos(clamp1(-Math.tan(phi) * Math.tan(d)));
// Sun's unit vector (east, north, up) for temporal-hour fraction f of the day.
function sunVec(lat, dec, f, halfDay) {
const phi = Math.abs(lat) * rad, d = lat < 0 ? -dec : dec;
const H0 = halfDay ?? halfDayAngle(phi, d);
const H = H0 * (2 * f - 1);
return {
e: -Math.cos(d) * Math.sin(H) * (lat < 0 ? -1 : 1),
n: Math.cos(phi) * Math.sin(d) - Math.sin(phi) * Math.cos(d) * Math.cos(H),
u: Math.sin(phi) * Math.sin(d) + Math.cos(phi) * Math.cos(d) * Math.cos(H)
};
}
const toScreen = (east, up) => [CX + east * R, CY - up * R];
function dialPoint(lat, dec, f, halfDay) {
const s = sunVec(lat, dec, f, halfDay);
return toScreen(-s.e, Math.min(0, -s.u));
}
const toPath = pts => 'M' + pts.map(p => p[0].toFixed(1) + ',' + p[1].toFixed(1)).join('L');
const range = (a, b, n) => Array.from({ length: n + 1 }, (_, i) => a + (b - a) * i / n);
const romanHourMin = (lat, dec) => {
const phi = Math.abs(lat) * rad, d = lat < 0 ? -dec : dec;
const cosH = (Math.sin(REFRACTION) - Math.sin(phi) * Math.sin(d)) / (Math.cos(phi) * Math.cos(d));
return Math.round(Math.acos(clamp1(cosH)) / Math.PI * 1440 / 12);
};
// Curves the reader can point at: the three seasonal day curves plus today's.
const curveEls = {};
let activeCurve = null, pinnedCurve = null;
function curveText(key) {
const lat = place.lat, south = lat < 0;
const bits = {
bruma: ['Bruma', 'winter solstice', south ? '21 Jun' : '21 Dec', 'shortest day', -SOLSTICE],
aequinoctium: ['Aequinoctium', 'equinox', '20 Mar & 22 Sep', 'day equals night', 0],
solstitium: ['Solstitium', 'summer solstice', south ? '21 Dec' : '21 Jun', 'longest day', SOLSTICE],
}[key];
if (key === 'today') {
const dec = solarDec(new Date(Date.now() + offsetMin * 6e4));
return `<b>Today's path</b> of the shadow · ${romanHourMin(lat, dec)}-minute hours`;
}
const dec = south ? -bits[4] : bits[4];
return `<b>${bits[0]}</b> · ${bits[1]} (~${bits[2]}) · ${bits[3]}, ${romanHourMin(lat, dec)}-minute hours`;
}
function setActiveCurve(key) {
activeCurve = key;
for (const k in curveEls) curveEls[k].classList.toggle('active', k === key);
$('curveInfo').innerHTML = key ? curveText(key) : 'Point at or tap a curve to identify it';
}
function addHit(key, d) {
let hit = $('hit-' + key);
if (!hit) {
hit = el('path', { id: 'hit-' + key, class: 'hit', tabindex: 0, role: 'button', 'aria-label': key }, $('hits'));
hit.addEventListener('pointerenter', () => setActiveCurve(key));
hit.addEventListener('pointerleave', () => setActiveCurve(pinnedCurve));
hit.addEventListener('focus', () => setActiveCurve(key));
hit.addEventListener('blur', () => setActiveCurve(pinnedCurve));
hit.addEventListener('click', e => {
e.stopPropagation();
pinnedCurve = pinnedCurve === key ? null : key;
setActiveCurve(pinnedCurve ?? key);
});
}
hit.setAttribute('d', d);
}
document.addEventListener('click', () => { if (pinnedCurve) { pinnedCurve = null; setActiveCurve(null); } });
const bandEls = [], numEls = [];
let dialLat = null;
function buildDial(lat) {
if (dialLat === lat) return;
dialLat = lat;
const bands = $('bands'), lines = $('dialLines'), nums = $('numerals');
bands.replaceChildren(); lines.replaceChildren(); nums.replaceChildren();
bandEls.length = numEls.length = 0;
const winter = lat < 0 ? SOLSTICE : -SOLSTICE;
const decs = range(-SOLSTICE, SOLSTICE, 16);
const hourLine = f => decs.map(d => dialPoint(lat, d, f));
const dayCurve = (d, f0, f1, n) => range(f0, f1, n).map(f => dialPoint(lat, d, f));
for (let k = 0; k < 12; k++) {
const f0 = k / 12, f1 = (k + 1) / 12;
const pts = [...hourLine(f0), ...dayCurve(SOLSTICE, f0, f1, 6), ...hourLine(f1).reverse(), ...dayCurve(-SOLSTICE, f1, f0, 6)];
bandEls.push(el('path', { class: 'band', d: toPath(pts) + 'Z' }, bands));
// numerals sit just outside the winter-solstice curve, nearest the rim
const [px, py] = dialPoint(lat, winter, (k + .5) / 12);
const vx = px - CX, vy = py - CY, len = Math.hypot(vx, vy) || 1;
const t = el('text', { class: 'numeral', x: px + vx / len * 10, y: py + vy / len * 10 }, nums);
t.textContent = NUMERALS[k];
numEls.push(t);
}
for (let k = 0; k <= 12; k++) el('path', { class: 'hour-line', d: toPath(hourLine(k / 12)) }, lines);
for (const [key, d] of [['bruma', winter], ['aequinoctium', 0], ['solstitium', -winter]]) {
const path = toPath(dayCurve(d, 0, 1, 60));
curveEls[key] = el('path', { class: 'day-curve', d: path }, lines);
addHit(key, path);
}
curveEls.today = $('todayCurve');
setActiveCurve(pinnedCurve);
}
// ---- clepsydra ----
// Water rises at a steady rate, so the hour marks sit at heights proportional to elapsed time.
// Nights change length through the year, so each hour line winds around the drum; the drum is
// turned daily so today's date faces the pointer. The inflow is set so the longest night fills it.
const TRAVEL = 150, POINTER0 = 200, DRUM_X = 284, DRUM_R = 24, DRUM_SPAN = 75 * rad;
const MONTHS = ['IAN', 'FEB', 'MAR', 'APR', 'MAI', 'IVN', 'IVL', 'AVG', 'SEP', 'OCT', 'NOV', 'DEC'];
const nightFrac = (lat, date) => 1 - romanHourMin(lat, solarDec(date)) * 12 / 1440;
const colNums = [], colBands = [];
let drumKey = null, maxNight = 1;
function buildDrum(lat, today) {
const key = lat + '|' + today.toDateString();
if (drumKey === key) return;
drumKey = key;
const col = $('column');
col.replaceChildren();
colNums.length = colBands.length = 0;
const yearStart = new Date(today.getFullYear(), 0, 1);
maxNight = Math.max(...range(0, 365, 365).map(d => nightFrac(lat, new Date(yearStart.getTime() + d * dayMs))));
const thetas = range(-DRUM_SPAN, DRUM_SPAN, 30);
const dateAt = th => new Date(today.getTime() + th / (2 * Math.PI) * 365.2422 * dayMs);
const nights = thetas.map(th => nightFrac(lat, dateAt(th)));
const xAt = th => DRUM_X + DRUM_R * Math.sin(th);
const yAt = (k, night) => POINTER0 - k / 12 * night / maxNight * TRAVEL;
const line = k => thetas.map((th, i) => [xAt(th), yAt(k, nights[i])]);
for (let k = 0; k < 12; k++) {
colBands.push(el('path', { class: 'band', d: toPath([...line(k), ...line(k + 1).reverse()]) + 'Z' }, col));
}
for (let k = 0; k <= 12; k++) el('path', { class: 'col-line' + (k % 3 === 0 ? ' vigil' : ''), d: toPath(line(k)), fill: 'none' }, col);
// month boundaries (Kalends) as they wrap round the drum
for (let m = -3; m <= 4; m++) {
const kal = new Date(today.getFullYear(), today.getMonth() + m, 1);
const th = (kal - today) / dayMs / 365.2422 * 2 * Math.PI;
if (Math.abs(th) > DRUM_SPAN * .92) continue;
const top = yAt(12, nightFrac(lat, kal));
el('line', { class: 'month-line', x1: xAt(th), x2: xAt(th), y1: POINTER0, y2: top }, col);
}
el('text', { class: 'month-label', x: DRUM_X, y: POINTER0 + 10 }, col).textContent = MONTHS[today.getMonth()];
const front = nightFrac(lat, today);
for (let k = 0; k < 12; k++) {
const y1 = yAt(k, front), y0 = yAt(k + 1, front);
const t = el('text', { class: 'numeral', x: DRUM_X, y: (y0 + y1) / 2, 'font-size': Math.max(6, Math.min(11, (y1 - y0) * .85)) }, col);
t.textContent = NUMERALS[k];
colNums.push(t);
}
}
(function buildStars() {
const stars = $('stars');
let seed = 7;
const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
for (let i = 0; i < 50; i++) {
el('circle', { class: 'star', cx: rnd() * 400, cy: rnd() * 400, r: rnd() * 1.2 + .3, opacity: rnd() * .6 + .3 }, stars);
}
})();
// Drips from the orifice, ripples where they land, and flowing supply/overflow streams.
let waterY = 380;
const NOZZLE = [126, 206];
const drops = [], ripples = [];
let lastSpawn = 0, lastFrame = 0;
function animateWater(t) {
requestAnimationFrame(animateWater);
if ($('clepsydra').hasAttribute('hidden') || document.hidden) { lastFrame = t; return; }
const dt = Math.max(0, Math.min(50, t - (lastFrame || t))) / 1000;
lastFrame = t;
if (t - lastSpawn > 420) {
lastSpawn = t;
drops.push({ y: NOZZLE[1], v: 0, node: el('circle', { class: 'drop', cx: NOZZLE[0], cy: NOZZLE[1], r: 2.2 }, $('drops')) });
}
for (let i = drops.length - 1; i >= 0; i--) {
const d = drops[i];
d.v += 600 * dt;
d.y += d.v * dt;
if (d.y >= waterY) {
d.node.remove();
drops.splice(i, 1);
ripples.push({ age: 0, node: el('ellipse', { class: 'ripple', cx: NOZZLE[0], cy: waterY, rx: 1, ry: .5 }, $('drops')) });
} else d.node.setAttribute('cy', d.y);
}
for (let i = ripples.length - 1; i >= 0; i--) {
const r = ripples[i];
r.age += dt;
if (r.age > .5) { r.node.remove(); ripples.splice(i, 1); continue; }
r.node.setAttribute('rx', 1 + r.age * 22);
r.node.setAttribute('ry', .5 + r.age * 4);
r.node.setAttribute('cy', waterY);
r.node.setAttribute('opacity', 1 - r.age * 2);
}
document.querySelectorAll('#clepsydra .stream').forEach(s => s.setAttribute('stroke-dashoffset', (-t / 40) % 8));
}
requestAnimationFrame(animateWater);
function drawDay(now, per, frac, idx) {
$('sundial').toggleAttribute('hidden', false);
$('clepsydra').toggleAttribute('hidden', true);
buildDial(place.lat);
const dec = solarDec(now);
const today = toPath(range(0, 1, 60).map(f => dialPoint(place.lat, dec, f)));
$('todayCurve').setAttribute('d', today);
addHit('today', today);
if (activeCurve === 'today') $('curveInfo').innerHTML = curveText('today');
const sun = sunVec(place.lat, dec, frac, Math.PI * (per.end - per.start) / dayMs);
sun.u = Math.max(0, sun.u);
const [tx, ty] = toScreen(-sun.e, -sun.u);
const dx = tx - CX, dy = ty - CY, len = Math.hypot(dx, dy) || 1;
const nx = -dy / len, ny = dx / len;
$('shadow').setAttribute('d', `M${CX + nx * 2.5},${CY + ny * 2.5} L${tx + nx * .8},${ty + ny * .8} L${tx - nx * .8},${ty - ny * .8} L${CX - nx * 2.5},${CY - ny * 2.5}Z`);
$('shadow').style.display = $('tip').style.display = '';
$('tip').setAttribute('cx', tx);
$('tip').setAttribute('cy', ty);
bandEls.forEach((b, i) => b.setAttribute('class', 'band' + (i < idx ? ' done' : i === idx ? ' now' : '')));
numEls.forEach((n, i) => n.setAttribute('class', 'numeral' + (i === idx ? ' now' : '')));
}
function drawNight(now, frac, idx) {
$('sundial').toggleAttribute('hidden', true);
$('clepsydra').toggleAttribute('hidden', false);
$('curveInfo').innerHTML = '';
buildDrum(place.lat, now);
const rise = Math.min(TRAVEL, frac * nightFrac(place.lat, now) / maxNight * TRAVEL);
waterY = 380 - rise;
$('float').setAttribute('transform', `translate(0 ${-rise})`);
$('water').setAttribute('y', waterY);
$('water').setAttribute('height', 10 + rise);
colBands.forEach((b, i) => b.setAttribute('class', 'band' + (i < idx ? ' done' : i === idx ? ' now' : '')));
colNums.forEach((n, i) => n.setAttribute('class', 'numeral' + (i === idx ? ' now' : '')));
}
// ---- state ----
const ROME = { lat: 41.9028, lng: 12.4964, name: 'Roma', tz: 'Europe/Rome' };
let place = loadPlace() || ROME;
let offsetMin = 0;
function loadPlace() {
try {
const p = JSON.parse(localStorage.getItem('romantime.place'));
if (p && isFinite(p.lat) && isFinite(p.lng)) return p.name === 'My location' ? p : { ...p, tz: approxZone(p.lng) };
} catch (e) { }
return null;
}
function savePlace(p) {
try { localStorage.setItem('romantime.place', JSON.stringify(p)); } catch (e) { }
}
// Without a timezone lookup service, approximate a picked spot's zone from its longitude.
function approxZone(lng) {
const h = Math.round(lng / 15);
return h === 0 ? 'Etc/GMT' : `Etc/GMT${h > 0 ? '-' : '+'}${Math.abs(h)}`;
}
function setPlace(lat, lng, name) {
lat = Math.max(-90, Math.min(90, +lat));
lng = ((+lng + 540) % 360) - 180;
place = { lat, lng, name: name || null, tz: name === 'My location' ? undefined : approxZone(lng) };
savePlace(place);
render();
}
// ---- formatting ----
const fmtTime = d => d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', timeZone: place.tz });
function tzNote() {
if (!place.tz) return 'Clock times in your time zone';
if (place.tz === 'Europe/Rome') return 'Clock times in Rome';
const h = -parseInt(place.tz.slice(7) || '0', 10);
return `Clock times approximate local time (UTC${h >= 0 ? '+' : '−'}${Math.abs(h)})`;
}
const fmtDur = ms => {
const m = Math.round(ms / 6e4), h = Math.floor(m / 60);
return h ? `${h}h ${m % 60}m` : `${m} min`;
};
const fmtCoord = p => `${Math.abs(p.lat).toFixed(2)}°${p.lat >= 0 ? 'N' : 'S'}, ${Math.abs(p.lng).toFixed(2)}°${p.lng >= 0 ? 'E' : 'W'}`;
// ---- render ----
function render() {
const now = new Date(Date.now() + offsetMin * 6e4);
$('locLabel').textContent = place.name || fmtCoord(place);
$('tzNote').textContent = tzNote();
const per = periodAt(now, place.lat, place.lng);
if (per.polar) return renderPolar(per.polar);
const len = per.end - per.start;
const frac = (now - per.start) / len;
const hourLen = len / 12;
const idx = Math.min(11, Math.floor(frac * 12));
const within = frac * 12 - idx;
document.body.classList.toggle('night', !per.isDay);
if (per.isDay) drawDay(now, per, frac, idx);
else drawNight(now, frac, idx);
$('bigNumeral').textContent = NUMERALS[idx];
const when = within < 1 / 3 ? 'Early in' : within < 2 / 3 ? 'Midway through' : 'Late in';
if (per.isDay) {
$('latin').textContent = `Hora ${ORDINALS[idx]}`;
$('phrase').textContent = `${when} the ${ENGLISH[idx]} hour of the day`;
} else {
const v = Math.floor(idx / 3);
$('latin').textContent = `Hora ${ORDINALS[idx]} Noctis`;
$('phrase').textContent = `${when} the ${ENGLISH[idx]} hour of night · Vigilia ${VIGILIAE[v]}`;
}
$('dialTitle').textContent = `Hemicyclium sundial showing ${$('latin').textContent}`;
const nextAt = new Date(per.start.getTime() + (idx + 1) * hourLen);
$('progLeft').innerHTML = `<b>${Math.round(within * 100)}%</b> through hour ${NUMERALS[idx]}`;
$('progRight').textContent = idx < 11
? `Hour ${NUMERALS[idx + 1]} at ${fmtTime(nextAt)}`
: `${per.isDay ? 'Sunset' : 'Sunrise'} at ${fmtTime(per.end)}`;
$('progBar').style.width = (within * 100).toFixed(1) + '%';
if (per.isDay) {
setStat(1, 'Sunrise', fmtTime(per.start));
setStat(2, 'Sunset', fmtTime(per.end));
setStat(3, 'One Roman hour', `${Math.round(hourLen / 6e4)} min`);
setStat(4, 'Daylight left', fmtDur(per.end - now));
} else {
setStat(1, 'Sunset', fmtTime(per.start));
setStat(2, 'Sunrise', fmtTime(per.end));
setStat(3, 'One night hour', `${Math.round(hourLen / 6e4)} min`);
setStat(4, 'Until dawn', fmtDur(per.end - now));
}
$('listTitle').textContent = per.isDay ? 'Horae Diei' : 'Horae Noctis';
const items = [];
for (let i = 0; i < 12; i++) {
const s = new Date(per.start.getTime() + i * hourLen);
const cls = i < idx ? 'past' : i === idx ? 'now' : '';
const label = `Hora ${ORDINALS[i]}` +
(!per.isDay && i % 3 === 0 ? `<small>Vigilia ${NUMERALS[i / 3]}</small>` : '');
items.push(`<li class="${cls}"><span class="n">${NUMERALS[i]}</span><span>${label}</span><span class="t">${fmtTime(s)}</span></li>`);
}
const html = items.join('');
if ($('hourList').innerHTML !== html) $('hourList').innerHTML = html;
}
function setStat(n, label, value) {
$('s' + n + 'l').textContent = label;
$('s' + n).textContent = value;
}
function renderPolar(kind) {
const day = kind === 'day';
document.body.classList.toggle('night', !day);
$('sundial').toggleAttribute('hidden', false);
$('clepsydra').toggleAttribute('hidden', true);
buildDial(place.lat);
$('todayCurve').setAttribute('d', '');
$('shadow').style.display = $('tip').style.display = 'none';
bandEls.forEach(b => b.setAttribute('class', 'band'));
numEls.forEach(n => n.setAttribute('class', 'numeral'));
$('bigNumeral').textContent = day ? '☉' : '☾';
$('latin').textContent = day ? 'Sol Perpetuus' : 'Nox Perpetua';
$('phrase').textContent = day ? "The sun doesn't set here today" : "The sun doesn't rise here today";
$('progLeft').textContent = 'No Roman hours today';
$('progRight').textContent = '';
$('progBar').style.width = '0';
['Sunrise', 'Sunset', 'One Roman hour', 'Daylight'].forEach((l, i) => setStat(i + 1, l, '–'));
$('hourList').innerHTML = '';
}
// ---- preview slider ----
$('scrub').addEventListener('input', e => {
offsetMin = +e.target.value;
const sign = offsetMin < 0 ? '−' : '+';
const a = Math.abs(offsetMin);
$('scrubLabel').textContent = offsetMin === 0 ? 'Now'
: `${sign}${Math.floor(a / 60)}h ${a % 60}m · ${fmtTime(new Date(Date.now() + offsetMin * 6e4))}`;
$('scrubReset').hidden = offsetMin === 0;
render();
});
$('scrubReset').addEventListener('click', () => {
$('scrub').value = 0;
$('scrub').dispatchEvent(new Event('input'));
});
// ---- location sheet ----
const sheet = $('locSheet');
let map, marker;
function syncForm() {
$('lat').value = place.lat.toFixed(4);
$('long').value = place.lng.toFixed(4);
if (map) {
marker.setLatLng([place.lat, place.lng]);
map.setView([place.lat, place.lng]);
}
}
$('openLoc').addEventListener('click', () => {
sheet.showModal();
if (!map && window.L) {
map = L.map('map', { zoomControl: true }).setView([place.lat, place.lng], 5);
L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', {
maxZoom: 19,
attribution: 'Tiles &copy; Esri &mdash; Source: Esri, HERE, Garmin, USGS, NGA, EPA, USDA, NPS'
}).addTo(map);
marker = L.circleMarker([place.lat, place.lng], { radius: 8, color: '#c2410c', weight: 3, fillOpacity: .5 }).addTo(map);
map.on('click', e => {
setPlace(e.latlng.lat, e.latlng.lng);
syncForm();
$('hint').textContent = 'Location updated.';
});
}
syncForm();
if (map) setTimeout(() => map.invalidateSize(), 50);
});
$('closeLoc').addEventListener('click', () => sheet.close());
sheet.addEventListener('click', e => { if (e.target === sheet) sheet.close(); });
$('coordForm').addEventListener('submit', e => {
e.preventDefault();
const lat = parseFloat($('lat').value), lng = parseFloat($('long').value);
if (!isFinite(lat) || !isFinite(lng) || Math.abs(lat) > 90) {
$('hint').textContent = 'Enter a latitude (−90 to 90) and longitude.';
return;
}
setPlace(lat, lng);
syncForm();
$('hint').textContent = 'Location updated.';
});
function locate(fromButton) {
if (!navigator.geolocation) {
if (fromButton) $('hint').textContent = "This browser can't share its location.";
return;
}
if (fromButton) $('hint').textContent = 'Finding you…';
navigator.geolocation.getCurrentPosition(pos => {
setPlace(pos.coords.latitude, pos.coords.longitude, 'My location');
syncForm();
if (fromButton) $('hint').textContent = 'Using your current location.';
}, err => {
if (fromButton) $('hint').textContent = 'Location unavailable: ' + err.message;
}, { maximumAge: 6e5, timeout: 15000 });
}
$('useGps').addEventListener('click', () => locate(true));
render();
if (!loadPlace() || place.name === 'My location') locate(false);
setInterval(render, 1000);
</script>
</body>
</html>