Skip to content

Commit

Permalink
Fix time representation
Browse files Browse the repository at this point in the history
- There's no need to visit all layers, just the timezone ones.
- Timezones are far from rectangular, testing against their bounds gives
  wrong results in far too many cases.
- The value in `time_zone` property is a fixed offset, not taking into
  account DST changes, so can't be used directly.
- You can now add a `timezone` property to users to override detection
  by coordinates (the timezones plugin has stale data, some timezones
  have changed).
- Changed output format to use client's locale, instead of Swedish.
  • Loading branch information
lonemadmax committed Jan 9, 2025
1 parent 7416c74 commit 680741e
Showing 1 changed file with 27 additions and 31 deletions.
58 changes: 27 additions & 31 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -110,41 +110,37 @@
L.marker(user.coordinates, { icon })
.addTo(map)
.bindPopup(() => {
// see https://stackoverflow.com/a/38671346/14457064
const userBounds = L.latLngBounds(
user.coordinates,
user.coordinates,
);

for (const overlay of Object.values(map._layers)) {
if (overlay._layers) {
for (const feature of Object.values(overlay._layers)) {
let bounds;
if (feature.getBounds) {
bounds = feature.getBounds();
} else if (feature._latlng) {
bounds = L.latLngBounds(
feature._latlng,
feature._latlng,
);
}

if (bounds && userBounds.intersects(bounds)) {
const paragraph =
container.getElementsByTagName("p")[0] ??
document.createElement("p");
paragraph.innerText = `${new Date().toLocaleString(
"sv",
{ timeZone: feature.feature.properties.tz_name1st },
)} (${feature.feature.properties.time_zone})`;

container.appendChild(paragraph);

return container;
if (user.timezone === undefined) {
const userPoint = map.latLngToLayerPoint(user.coordinates);
for (const timezoneLayer of Object.values(L.timezones._layers)) {
if (timezoneLayer._containsPoint(userPoint)) {
if (user.timezone === undefined) {
// Some timezones have no tz_name1st.
// utc_format has their offset as "UTCsHH:MM", but
// toLocaleString doesn't like that UTC prefix nor the
// "±" sign in the ones with 0 offset.
const properties = timezoneLayer.feature.properties;
user.timezone = properties.tz_name1st
?? (properties.zone == 0 ? "+00" : properties.utc_format.substring(3));
} else {
// Several timezones may contain a point near the limit
// at some zoom levels
user.timezone = undefined;
break;
}
}
}
}
if (user.timezone !== undefined) {
const paragraph =
container.getElementsByTagName("p")[0] ??
document.createElement("p");
paragraph.innerText = `${new Date().toLocaleString(
undefined,
{ timeZone: user.timezone, timeZoneName: 'shortOffset'},
)}`;
container.appendChild(paragraph);
}

return container;
});
Expand Down

0 comments on commit 680741e

Please sign in to comment.