855 lines
36 KiB
JavaScript
855 lines
36 KiB
JavaScript
(function (window) {
|
|
// The leaflet-gesture-handling UMD build exposes its class as
|
|
// window.leafletGestureHandling.GestureHandling instead of registering
|
|
// itself on L (unlike the other Leaflet plugins loaded on this page), so
|
|
// it has to be wired in manually before any L.map() call.
|
|
if (window.L && window.leafletGestureHandling && !window.L.Map.prototype.options.gestureHandling) {
|
|
window.L.Map.addInitHook('addHandler', 'gestureHandling', window.leafletGestureHandling.GestureHandling);
|
|
}
|
|
|
|
// Köln — last-resort fallback if a caller doesn't pass its own center;
|
|
// both controllers (Home/Map) explicitly pass the same point themselves,
|
|
// so this only matters if that ever gets forgotten.
|
|
var DEFAULT_CENTER = [50.9375, 6.9603];
|
|
|
|
// Remembers the last place a user searched/geolocated to, shared between
|
|
// the home hero map and /map, so switching between them (or coming back
|
|
// later) doesn't reset to Köln and make them search again.
|
|
var LAST_LOCATION_KEY = 'vindn:lastLocation';
|
|
|
|
function loadLastLocation() {
|
|
try {
|
|
var raw = window.localStorage && localStorage.getItem(LAST_LOCATION_KEY);
|
|
if (!raw) return null;
|
|
var parsed = JSON.parse(raw);
|
|
if (typeof parsed.lat === 'number' && typeof parsed.lon === 'number' && isFinite(parsed.lat) && isFinite(parsed.lon)) {
|
|
return parsed;
|
|
}
|
|
} catch (e) { /* localStorage disabled/unavailable, or corrupt value — just skip it */ }
|
|
return null;
|
|
}
|
|
|
|
function saveLastLocation(lat, lon) {
|
|
try {
|
|
if (window.localStorage) localStorage.setItem(LAST_LOCATION_KEY, JSON.stringify({ lat: lat, lon: lon }));
|
|
} catch (e) { /* localStorage disabled/unavailable — nothing to persist to */ }
|
|
}
|
|
|
|
function setLocateStatus(statusEl, text, isError) {
|
|
if (!statusEl) return;
|
|
statusEl.textContent = text;
|
|
statusEl.classList.toggle('is-error', !!isError);
|
|
}
|
|
|
|
// Leaflet.awesome-markers only ships a fixed palette of named colors (no
|
|
// arbitrary hex/hsl) — curated to the ones that read well against the
|
|
// grayscale-filtered basemap. Approximate hex values below are only used
|
|
// for the legend swatches, so they match what's actually drawn on pins.
|
|
var AWESOME_COLORS = ['red', 'darkred', 'orange', 'green', 'darkgreen', 'blue', 'darkblue', 'lightblue', 'purple', 'darkpurple', 'cadetblue', 'beige'];
|
|
var AWESOME_COLOR_HEX = {
|
|
red: '#d63e2a', darkred: '#a23336', orange: '#f69730', green: '#72b026',
|
|
darkgreen: '#728224', blue: '#38aadd', darkblue: '#0067a3', lightblue: '#8adaff',
|
|
purple: '#d252b9', darkpurple: '#5b396b', cadetblue: '#436978', beige: '#e0a458'
|
|
};
|
|
|
|
// Real ODH category names are German tourism-taxonomy strings (80+ of
|
|
// them) — this maps keywords found in a name to a Font Awesome 4 glyph,
|
|
// first match wins, falling back to a generic calendar icon.
|
|
var CATEGORY_ICON_RULES = [
|
|
{ icon: 'tree', words: ['weihnacht'] },
|
|
{ icon: 'music', words: ['musik', 'konzert', 'jazz', 'rock', 'pop', 'blues', 'soul', 'reggae', 'techno', 'house', 'elektro', 'punk', 'metal', 'folk', 'country', 'swing', 'gospel', 'klassisch', 'oper', 'musical', 'schlager', 'sakralmusik', 'volksmusik', 'dancehall', 'r\'n\'b'] },
|
|
{ icon: 'comments', words: ['theater', 'bühne', 'schauspiel', 'kabarett', 'ballett', 'figurentheater'] },
|
|
{ icon: 'film', words: ['film'] },
|
|
{ icon: 'shopping-cart', words: ['markt', 'flohmarkt', 'messe'] },
|
|
{ icon: 'flag', words: ['festival', 'fest', 'kirmes', 'jahrmarkt', 'stadtfest'] },
|
|
{ icon: 'binoculars', words: ['führung', 'besichtigung', 'ausflug', 'exkursion'] },
|
|
{ icon: 'bicycle', words: ['radtour', 'rad'] },
|
|
{ icon: 'trophy', words: ['sport', 'turnier', 'wettbewerb', 'motorsport'] },
|
|
{ icon: 'map-signs', words: ['wanderung'] },
|
|
{ icon: 'cutlery', words: ['gastronomie', 'genuss', 'gourmet'] },
|
|
{ icon: 'child', words: ['kinder', 'familie'] },
|
|
{ icon: 'heartbeat', words: ['gesundheit', 'wellness'] },
|
|
{ icon: 'university', words: ['kirche', 'sakral'] },
|
|
{ icon: 'book', words: ['vortrag', 'lesung', 'kurs', 'seminar', 'workshop', 'hobby'] },
|
|
{ icon: 'users', words: ['kongress', 'geselligkeit', 'spiele', 'treffen'] },
|
|
{ icon: 'glass', words: ['party', 'nightlife'] },
|
|
{ icon: 'picture-o', words: ['ausstellung'] }
|
|
];
|
|
var DEFAULT_ICON = 'calendar';
|
|
|
|
function hashHue(str) {
|
|
var hash = 0;
|
|
for (var i = 0; i < str.length; i++) {
|
|
hash = (hash * 31 + str.charCodeAt(i)) >>> 0;
|
|
}
|
|
return hash;
|
|
}
|
|
|
|
function categoryColor(name) {
|
|
if (!name) return 'hsl(220, 10%, 55%)';
|
|
return 'hsl(' + (hashHue(name) % 360) + ', 62%, 42%)';
|
|
}
|
|
|
|
function categoryMarkerColorName(name) {
|
|
if (!name) return 'cadetblue';
|
|
return AWESOME_COLORS[hashHue(name) % AWESOME_COLORS.length];
|
|
}
|
|
|
|
function categoryMarkerHex(name) {
|
|
return AWESOME_COLOR_HEX[categoryMarkerColorName(name)] || '#436978';
|
|
}
|
|
|
|
function categoryIconName(name) {
|
|
var lower = (name || '').toLowerCase();
|
|
for (var i = 0; i < CATEGORY_ICON_RULES.length; i++) {
|
|
var rule = CATEGORY_ICON_RULES[i];
|
|
for (var j = 0; j < rule.words.length; j++) {
|
|
if (lower.indexOf(rule.words[j]) !== -1) return rule.icon;
|
|
}
|
|
}
|
|
return DEFAULT_ICON;
|
|
}
|
|
|
|
function ensurePulseStyle() {
|
|
if (document.getElementById('vindn-pulse-style')) return;
|
|
var styleTag = document.createElement('style');
|
|
styleTag.id = 'vindn-pulse-style';
|
|
styleTag.textContent = '@keyframes vindnPulse{0%{transform:scale(.6);opacity:.45}100%{transform:scale(2.4);opacity:0}}';
|
|
document.head.appendChild(styleTag);
|
|
}
|
|
|
|
// Plain pulsing dot — used only for the "you are here" user-location
|
|
// marker, kept visually distinct from the category pins below.
|
|
function dotIcon(color, big) {
|
|
var size = big ? 18 : 14;
|
|
var ring = big
|
|
? '<span style="position:absolute;inset:-8px;border-radius:50%;background:' + color + ';opacity:.25;animation:vindnPulse 2.2s ease-out infinite;"></span>'
|
|
: '';
|
|
return L.divIcon({
|
|
className: 'pin-icon',
|
|
html: '<span style="position:relative;display:block;width:' + size + 'px;height:' + size + 'px;">' + ring +
|
|
'<span style="position:absolute;inset:0;border-radius:50%;background:' + color + ';border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.35);"></span></span>',
|
|
iconSize: [size, size],
|
|
iconAnchor: [size / 2, size / 2]
|
|
});
|
|
}
|
|
|
|
// Category pin — Font Awesome glyph in a colored teardrop marker, falling
|
|
// back to a plain dot if the awesome-markers plugin didn't load.
|
|
function categoryIcon(name) {
|
|
if (window.L.AwesomeMarkers) {
|
|
return L.AwesomeMarkers.icon({
|
|
icon: categoryIconName(name),
|
|
prefix: 'fa',
|
|
markerColor: categoryMarkerColorName(name)
|
|
});
|
|
}
|
|
return dotIcon(categoryColor(name), false);
|
|
}
|
|
|
|
// OpenFreeMap's "liberty" style labels everything with
|
|
// coalesce(name_en, name) — English first — which shows "Cologne"
|
|
// instead of "Köln" even though the whole map (and every event on it)
|
|
// is German. Rewrites that one recurring sub-expression, wherever it
|
|
// appears, to prefer name_de then the OSM-local `name` (which for
|
|
// German places already *is* the German name) before falling back to
|
|
// English. Layers that don't contain it (road-shield ref numbers, etc.)
|
|
// are left alone.
|
|
function preferGermanLabels(maplibreMap) {
|
|
var EN_FIRST = '["coalesce",["get","name_en"],["get","name"]]';
|
|
var DE_FIRST = '["coalesce",["get","name_de"],["get","name"],["get","name_en"]]';
|
|
|
|
var style = maplibreMap.getStyle();
|
|
if (!style || !style.layers) return;
|
|
|
|
style.layers.forEach(function (layer) {
|
|
var textField = layer.layout && layer.layout['text-field'];
|
|
if (!textField) return;
|
|
|
|
var serialized = JSON.stringify(textField);
|
|
if (serialized.indexOf(EN_FIRST) === -1) return;
|
|
|
|
maplibreMap.setLayoutProperty(layer.id, 'text-field', JSON.parse(serialized.split(EN_FIRST).join(DE_FIRST)));
|
|
});
|
|
}
|
|
|
|
function readEmbeddedJson(elementId) {
|
|
var el = document.getElementById(elementId);
|
|
if (!el) return [];
|
|
try {
|
|
return JSON.parse(el.textContent) || [];
|
|
} catch (e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function toRad(d) { return d * Math.PI / 180; }
|
|
|
|
function distanceKm(lat1, lon1, lat2, lon2) {
|
|
var R = 6371;
|
|
var dLat = toRad(lat2 - lat1);
|
|
var dLon = toRad(lon2 - lon1);
|
|
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
|
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
|
|
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
|
}
|
|
|
|
// Returns the `count` events closest to `center`, each tagged with `_dist` (km).
|
|
function nearest(center, events, count) {
|
|
return events
|
|
.map(function (ev) {
|
|
ev._dist = distanceKm(center[0], center[1], ev.lat, ev.lon);
|
|
return ev;
|
|
})
|
|
.sort(function (a, b) { return a._dist - b._dist; })
|
|
.slice(0, count);
|
|
}
|
|
|
|
// Builds an (unattached) marker for an event — caller adds it to either
|
|
// the map directly or a MarkerClusterGroup.
|
|
function buildMarker(ev, onMarkerClick) {
|
|
var hex = categoryMarkerHex(ev.category);
|
|
var marker = L.marker([ev.lat, ev.lon], { icon: categoryIcon(ev.category) });
|
|
var popupHtml = '<div class="pin-pop">' +
|
|
(ev.category ? '<span class="cat" style="color:' + hex + ';">' + ev.category + '</span>' : '') +
|
|
'<h4>' + ev.title + '</h4>' +
|
|
(ev.venue ? '<p>' + ev.venue + '</p>' : '') +
|
|
(ev.url ? '<a href="' + ev.url + '">View event →</a>' : '') +
|
|
'</div>';
|
|
marker.bindPopup(popupHtml);
|
|
if (onMarkerClick) marker.on('click', function () { onMarkerClick(ev, marker); });
|
|
return marker;
|
|
}
|
|
|
|
function fitToMarkers(map, markers) {
|
|
var list = Object.keys(markers).map(function (id) { return markers[id]; });
|
|
if (!list.length) return;
|
|
if (list.length === 1) { map.setView(list[0].getLatLng(), 13); return; }
|
|
map.fitBounds(L.featureGroup(list).getBounds(), { padding: [40, 40], maxZoom: 14, animate: false });
|
|
}
|
|
|
|
// Renders a Leaflet map of category pins (one per event) into
|
|
// containerId, clustered via Leaflet.markercluster when it's loaded.
|
|
// events: [{id, title, venue, category, lat, lon, url}]
|
|
function renderPinMap(containerId, events, opts) {
|
|
opts = opts || {};
|
|
var el = document.getElementById(containerId);
|
|
if (!el || !window.L) return null;
|
|
ensurePulseStyle();
|
|
|
|
var center = opts.center || (events.length ? [events[0].lat, events[0].lon] : DEFAULT_CENTER);
|
|
var map = L.map(containerId, {
|
|
zoomControl: !!opts.zoomControl,
|
|
attributionControl: !!opts.attributionControl,
|
|
scrollWheelZoom: !!opts.scrollWheelZoom,
|
|
// A raster L.tileLayer used to supply maxZoom implicitly; the
|
|
// MapLibre GL bridge doesn't. minZoom/maxBounds are maplibre-gl-
|
|
// leaflet's own documented recommendation, to avoid Leaflet/MapLibre
|
|
// disagreeing about zoom 0 and latitudes MapLibre doesn't support.
|
|
minZoom: 1,
|
|
maxZoom: 19,
|
|
maxBounds: [[-90, -Infinity], [90, Infinity]],
|
|
maxBoundsViscosity: 1,
|
|
// Requires two-finger drag / Ctrl+scroll to pan/zoom, with an
|
|
// on-map hint, so an embedded map (home hero, mid-page /map) doesn't
|
|
// trap page scroll/pinch-zoom on touch devices.
|
|
gestureHandling: opts.gestureHandling !== false
|
|
}).setView(center, opts.zoom || 13);
|
|
|
|
if (L.maplibreGL) {
|
|
// OpenFreeMap serves vector tiles only, rendered by MapLibre GL and
|
|
// bridged into this Leaflet map as an ordinary layer — everything
|
|
// else (markers, clustering, fullscreen) is untouched by this.
|
|
var glLayer = L.maplibreGL({
|
|
style: 'https://tiles.openfreemap.org/styles/liberty',
|
|
attribution: '© <a href="https://openfreemap.org" target="_blank">OpenFreeMap</a> <a href="https://www.openmaptiles.org/" target="_blank">© OpenMapTiles</a> Data from <a href="https://www.openstreetmap.org/copyright" target="_blank">OpenStreetMap</a>'
|
|
}).addTo(map);
|
|
|
|
var glMap = glLayer.getMaplibreMap && glLayer.getMaplibreMap();
|
|
if (glMap) {
|
|
// 'load' waits for full tile loading and can take a while;
|
|
// 'styledata' fires as soon as the style/layers themselves are
|
|
// parsed, which is all setLayoutProperty needs.
|
|
glMap.once('styledata', function () { preferGermanLabels(glMap); });
|
|
}
|
|
} else {
|
|
// Fallback if the MapLibre bridge failed to load for some reason.
|
|
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
|
|
maxZoom: 18,
|
|
attribution: opts.attributionControl ? '© OpenStreetMap contributors' : ''
|
|
}).addTo(map);
|
|
}
|
|
|
|
if (opts.fullscreenControl !== false && L.control && L.control.fullscreen) {
|
|
// Fullscreen the whole .stage (search bar, locate button, panel), not
|
|
// just the bare map div — those overlay controls are DOM siblings of
|
|
// #mapCanvas, not descendants, so they'd vanish in fullscreen otherwise.
|
|
L.control.fullscreen({
|
|
title: 'View fullscreen',
|
|
titleCancel: 'Exit fullscreen',
|
|
fullscreenElement: el.closest('.stage') || el
|
|
}).addTo(map);
|
|
|
|
// Fullscreen means the map owns the whole viewport, so the two-
|
|
// finger/Ctrl+scroll gating gesture handling exists for (avoiding
|
|
// trapped page scroll) no longer applies — switch back to normal
|
|
// single-finger/scroll interaction while fullscreen is active.
|
|
if (map.gestureHandling) {
|
|
map.on('enterFullscreen', function () { map.gestureHandling.disable(); });
|
|
map.on('exitFullscreen', function () { map.gestureHandling.enable(); });
|
|
}
|
|
}
|
|
|
|
var clusterGroup = (opts.cluster !== false && L.markerClusterGroup)
|
|
// animate:false — a fitBounds() called right after the initial
|
|
// addLayer() (see fitToMarkers) otherwise races the cluster expand/
|
|
// collapse animation and leaves stale icon elements in the DOM.
|
|
? L.markerClusterGroup({ maxClusterRadius: 50, spiderfyOnMaxZoom: true, showCoverageOnHover: false, animate: false })
|
|
: null;
|
|
if (clusterGroup) map.addLayer(clusterGroup);
|
|
|
|
var markers = {};
|
|
events.forEach(function (ev) {
|
|
var marker = buildMarker(ev, opts.onMarkerClick);
|
|
markers[ev.id] = marker;
|
|
if (clusterGroup) clusterGroup.addLayer(marker);
|
|
else marker.addTo(map);
|
|
});
|
|
|
|
return { map: map, markers: markers, clusterGroup: clusterGroup };
|
|
}
|
|
|
|
/**
|
|
* Wires up the full interactive map "stage" used on both the home page
|
|
* and /map: pin map, category chips (#catChips), legend (#legend),
|
|
* nearby-events panel (#panelList/#resultCount), and a "use my location"
|
|
* button (#locateBtn). All element ids are optional — missing
|
|
* ones are just skipped, so the same call works whether or not a given
|
|
* piece of UI is present on the page.
|
|
*
|
|
* opts.limit turns on the "light" mode used by the home page: instead of
|
|
* plotting every event, it shows only the `limit` nearest to a default
|
|
* center (opts.defaultCenter) until the user shares their real location,
|
|
* at which point it re-picks the `limit` nearest to *that* from the full
|
|
* event list and refits the map to them.
|
|
*/
|
|
function initMapStage(opts) {
|
|
opts = opts || {};
|
|
var allEvents = opts.events || [];
|
|
var limit = opts.limit || null;
|
|
var defaultCenter = opts.defaultCenter || DEFAULT_CENTER;
|
|
var containerId = opts.containerId || 'mapCanvas';
|
|
var state = { cat: 'all', userLoc: null };
|
|
// getCurrentPosition() can take a few seconds; if the user searches for
|
|
// a place before it resolves, its result must not overwrite whatever
|
|
// they deliberately chose in the meantime.
|
|
var manualLocationSet = false;
|
|
|
|
var shown = limit ? nearest(defaultCenter, allEvents.slice(), limit) : allEvents;
|
|
|
|
var result = renderPinMap(containerId, shown, {
|
|
zoomControl: true,
|
|
attributionControl: true,
|
|
zoom: opts.zoom || (limit ? 11 : (allEvents.length ? 9 : 7)),
|
|
center: limit ? defaultCenter : undefined,
|
|
onMarkerClick: function (ev) { highlightRow(ev.id); }
|
|
});
|
|
var map = result ? result.map : null;
|
|
var markers = result ? result.markers : {};
|
|
var clusterGroup = result ? result.clusterGroup : null;
|
|
var userMarker = null;
|
|
|
|
if (limit && map) fitToMarkers(map, markers);
|
|
|
|
var legendEl = document.getElementById('legend');
|
|
if (legendEl) {
|
|
var seenCats = [];
|
|
allEvents.forEach(function (ev) {
|
|
if (ev.category && seenCats.indexOf(ev.category) === -1) seenCats.push(ev.category);
|
|
});
|
|
legendEl.innerHTML = seenCats.slice(0, 8).map(function (cat) {
|
|
return '<span><span class="dot" style="background:' + categoryMarkerHex(cat) + ';"></span>' + cat + '</span>';
|
|
}).join('');
|
|
}
|
|
|
|
function addMarker(marker) {
|
|
if (clusterGroup) clusterGroup.addLayer(marker);
|
|
else if (map) marker.addTo(map);
|
|
}
|
|
|
|
function removeMarker(marker) {
|
|
if (clusterGroup) clusterGroup.removeLayer(marker);
|
|
else if (map) map.removeLayer(marker);
|
|
}
|
|
|
|
function rebuildMarkers(list) {
|
|
Object.keys(markers).forEach(function (id) { removeMarker(markers[id]); });
|
|
markers = {};
|
|
list.forEach(function (ev) {
|
|
var marker = buildMarker(ev, function (clicked) { highlightRow(clicked.id); });
|
|
markers[ev.id] = marker;
|
|
addMarker(marker);
|
|
});
|
|
shown = list;
|
|
}
|
|
|
|
function highlightRow(id) {
|
|
document.querySelectorAll('.map-row').forEach(function (r) { r.classList.remove('is-highlighted'); });
|
|
var row = document.querySelector('.map-row[data-id="' + id + '"]');
|
|
if (row) { row.classList.add('is-highlighted'); row.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); }
|
|
}
|
|
|
|
function currentList() {
|
|
if (limit) {
|
|
var list = shown.slice();
|
|
if (state.userLoc) {
|
|
list = list.map(function (ev) { ev._dist = distanceKm(state.userLoc[0], state.userLoc[1], ev.lat, ev.lon); return ev; })
|
|
.sort(function (a, b) { return a._dist - b._dist; });
|
|
}
|
|
return list;
|
|
}
|
|
|
|
var visible = allEvents.filter(function (ev) { return state.cat === 'all' || ev.category === state.cat; });
|
|
if (state.userLoc) {
|
|
visible = visible.map(function (ev) { ev._dist = distanceKm(state.userLoc[0], state.userLoc[1], ev.lat, ev.lon); return ev; })
|
|
.sort(function (a, b) { return a._dist - b._dist; });
|
|
}
|
|
|
|
Object.keys(markers).forEach(function (id) {
|
|
var isVisible = visible.some(function (ev) { return String(ev.id) === String(id); });
|
|
var m = markers[id];
|
|
var hasLayer = clusterGroup ? clusterGroup.hasLayer(m) : (map && map.hasLayer(m));
|
|
if (isVisible && !hasLayer) addMarker(m);
|
|
if (!isVisible && hasLayer) removeMarker(m);
|
|
});
|
|
|
|
return visible;
|
|
}
|
|
|
|
function renderList() {
|
|
var list = currentList();
|
|
|
|
var countEl = document.getElementById('resultCount');
|
|
if (countEl) countEl.textContent = list.length + (list.length === 1 ? ' event' : ' events');
|
|
|
|
var panelEl = document.getElementById('panelList');
|
|
if (!panelEl) return;
|
|
|
|
panelEl.innerHTML = list.map(function (ev) {
|
|
var distHtml = '';
|
|
if (ev._dist != null) {
|
|
var distLabel = ev._dist < 1 ? Math.round(ev._dist * 1000) : ev._dist.toFixed(1);
|
|
var distUnit = ev._dist < 1 ? 'm' : 'km';
|
|
distHtml = '<div class="dist">' + distLabel + '<span class="u">' + distUnit + '</span></div>';
|
|
}
|
|
return (
|
|
'<div class="map-row' + (ev._dist != null ? '' : ' no-dist') + '" data-id="' + ev.id + '" tabindex="0" role="button" aria-label="' + ev.title + '">' +
|
|
distHtml +
|
|
'<div><div class="name">' + ev.title + '</div><span class="when">' + (ev.venue || '') + '</span></div>' +
|
|
'<div class="go">→</div>' +
|
|
'</div>'
|
|
);
|
|
}).join('');
|
|
|
|
panelEl.querySelectorAll('.map-row').forEach(function (row) {
|
|
row.addEventListener('click', function () {
|
|
var id = row.getAttribute('data-id');
|
|
var ev = allEvents.filter(function (e) { return String(e.id) === String(id); })[0];
|
|
if (!ev || !map) return;
|
|
map.flyTo([ev.lat, ev.lon], 15);
|
|
var marker = markers[id];
|
|
if (marker) {
|
|
if (clusterGroup && clusterGroup.zoomToShowLayer) {
|
|
clusterGroup.zoomToShowLayer(marker, function () { marker.openPopup(); });
|
|
} else {
|
|
marker.openPopup();
|
|
}
|
|
}
|
|
highlightRow(id);
|
|
});
|
|
});
|
|
}
|
|
|
|
var chipsEl = document.getElementById('catChips');
|
|
if (chipsEl) {
|
|
chipsEl.addEventListener('click', function (e) {
|
|
var btn = e.target.closest('.chip-sm');
|
|
if (!btn) return;
|
|
chipsEl.querySelectorAll('.chip-sm').forEach(function (c) { c.classList.remove('is-active'); });
|
|
btn.classList.add('is-active');
|
|
state.cat = btn.getAttribute('data-cat');
|
|
renderList();
|
|
});
|
|
}
|
|
|
|
function setUserLocation(lat, lon, statusText) {
|
|
state.userLoc = [lat, lon];
|
|
saveLastLocation(lat, lon);
|
|
|
|
if (limit) rebuildMarkers(nearest([lat, lon], allEvents.slice(), limit));
|
|
|
|
var statusEl = document.getElementById('locateStatus');
|
|
setLocateStatus(statusEl, statusText, false);
|
|
|
|
if (map) {
|
|
if (userMarker) map.removeLayer(userMarker);
|
|
userMarker = L.marker([lat, lon], { icon: dotIcon('#2440FF', true), zIndexOffset: 1000 }).addTo(map);
|
|
if (limit) fitToMarkers(map, markers);
|
|
else map.setView([lat, lon], 13);
|
|
}
|
|
|
|
renderList();
|
|
}
|
|
|
|
function requestLocation(isAutoCheck) {
|
|
var statusEl = document.getElementById('locateStatus');
|
|
if (!navigator.geolocation) {
|
|
setLocateStatus(statusEl, 'Location not supported by your browser', true);
|
|
return;
|
|
}
|
|
setLocateStatus(statusEl, 'Finding you…', false);
|
|
navigator.geolocation.getCurrentPosition(function (pos) {
|
|
// A manual search/click may have already happened while this
|
|
// (silent, permission-check-triggered) lookup was still resolving.
|
|
if (isAutoCheck && manualLocationSet) return;
|
|
setUserLocation(pos.coords.latitude, pos.coords.longitude, limit ? ('Showing the ' + limit + ' nearest events') : 'Showing events near you');
|
|
}, function () {
|
|
setLocateStatus(statusEl, "Couldn't get your location", true);
|
|
}, { timeout: 8000 });
|
|
}
|
|
|
|
var locateBtn = document.getElementById('locateBtn');
|
|
if (locateBtn) locateBtn.addEventListener('click', function () { manualLocationSet = true; requestLocation(false); });
|
|
|
|
// Nominatim: explicit submit only, never as-you-type — required by its
|
|
// usage policy (max ~1 req/s, no autocomplete-style querying).
|
|
var locationForm = document.getElementById('locationSearchForm');
|
|
if (locationForm) {
|
|
locationForm.addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
var input = document.getElementById('locationSearch');
|
|
var query = (input.value || '').trim();
|
|
if (!query) return;
|
|
manualLocationSet = true;
|
|
var statusEl = document.getElementById('locateStatus');
|
|
setLocateStatus(statusEl, 'Looking up "' + query + '"…', false);
|
|
fetch('https://nominatim.openstreetmap.org/search?format=json&limit=1&q=' + encodeURIComponent(query))
|
|
.then(function (res) { return res.json(); })
|
|
.then(function (results) {
|
|
if (!results || !results.length) {
|
|
setLocateStatus(statusEl, 'Could not find "' + query + '"', true);
|
|
return;
|
|
}
|
|
setUserLocation(parseFloat(results[0].lat), parseFloat(results[0].lon), limit ? ('Showing the ' + limit + ' nearest events') : 'Showing events near you');
|
|
})
|
|
.catch(function () {
|
|
setLocateStatus(statusEl, 'Location search failed', true);
|
|
});
|
|
});
|
|
}
|
|
|
|
// A remembered search/geolocation takes priority over asking the
|
|
// browser again — restoring it counts as the user's own manual choice,
|
|
// so a slower-to-resolve auto-geolocation check below can't clobber it.
|
|
var lastLocation = loadLastLocation();
|
|
if (lastLocation) {
|
|
manualLocationSet = true;
|
|
setUserLocation(lastLocation.lat, lastLocation.lon, limit ? ('Showing the ' + limit + ' nearest events') : 'Showing events near you');
|
|
} else if (navigator.permissions && navigator.permissions.query) {
|
|
// If the user already granted location access (on this or an earlier
|
|
// visit), center on it automatically — this only *reads* the current
|
|
// permission state, it never triggers the browser's permission prompt
|
|
// itself, so it's safe to check unconditionally on load.
|
|
navigator.permissions.query({ name: 'geolocation' }).then(function (status) {
|
|
if (status.state === 'granted') requestLocation(true);
|
|
}).catch(function () {});
|
|
}
|
|
|
|
renderList();
|
|
|
|
return { map: map, markers: markers };
|
|
}
|
|
|
|
/**
|
|
* The /map page's full radius-based explorer — replaces a flat "first
|
|
* N events" cap with "events within rangeKm of a source point", where
|
|
* the source starts at the server-resolved center (Köln by default, or
|
|
* ?lat/&lon) and can move via a map click/marker drag, a place search
|
|
* (Nominatim), or "use my location". Assumes the full (non-compact)
|
|
* _map_stage.html.twig markup — #catChips, #legend, #rangeSelect,
|
|
* #locationSearchForm all present.
|
|
*
|
|
* opts.events is the full pool the server already limited to
|
|
* opts.maxRangeKm around opts.center; moving the source further than
|
|
* that away can't be served from the pool, so it triggers a fresh page
|
|
* load centered on the new point instead of silently showing partial
|
|
* results.
|
|
*/
|
|
function initRadiusMapStage(opts) {
|
|
opts = opts || {};
|
|
var allEvents = opts.events || [];
|
|
var originalCenter = opts.center || DEFAULT_CENTER;
|
|
var maxRangeKm = opts.maxRangeKm || 100;
|
|
var containerId = opts.containerId || 'mapCanvas';
|
|
|
|
var state = { source: originalCenter.slice(), rangeKm: opts.rangeKm || 25, cat: 'all' };
|
|
// getCurrentPosition() can take a few seconds; if the user searches or
|
|
// clicks the map before it resolves, its result must not overwrite
|
|
// whatever they deliberately chose in the meantime.
|
|
var manualLocationSet = false;
|
|
|
|
var result = renderPinMap(containerId, [], {
|
|
zoomControl: true,
|
|
attributionControl: true,
|
|
center: state.source,
|
|
zoom: opts.zoom || 11,
|
|
// This map already owns the whole viewport (no surrounding page to
|
|
// protect from trapped scroll/pinch), so gesture handling would only
|
|
// make one-finger dragging feel unresponsive for no benefit.
|
|
gestureHandling: false,
|
|
onMarkerClick: function (ev) { highlightRow(ev.id); }
|
|
});
|
|
var map = result ? result.map : null;
|
|
var markers = result ? result.markers : {};
|
|
var clusterGroup = result ? result.clusterGroup : null;
|
|
|
|
var sourceMarker = map
|
|
? L.marker(state.source, { icon: dotIcon('#14140F', true), draggable: true, zIndexOffset: 1000 }).addTo(map)
|
|
: null;
|
|
|
|
function addMarker(marker) {
|
|
if (clusterGroup) clusterGroup.addLayer(marker);
|
|
else if (map) marker.addTo(map);
|
|
}
|
|
|
|
function removeMarker(marker) {
|
|
if (clusterGroup) clusterGroup.removeLayer(marker);
|
|
else if (map) map.removeLayer(marker);
|
|
}
|
|
|
|
function rebuildMarkers(list) {
|
|
Object.keys(markers).forEach(function (id) { removeMarker(markers[id]); });
|
|
markers = {};
|
|
list.forEach(function (ev) {
|
|
var marker = buildMarker(ev, function (clicked) { highlightRow(clicked.id); });
|
|
markers[ev.id] = marker;
|
|
addMarker(marker);
|
|
});
|
|
}
|
|
|
|
function highlightRow(id) {
|
|
document.querySelectorAll('.map-row').forEach(function (r) { r.classList.remove('is-highlighted'); });
|
|
var row = document.querySelector('.map-row[data-id="' + id + '"]');
|
|
if (row) { row.classList.add('is-highlighted'); row.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); }
|
|
}
|
|
|
|
function inRange() {
|
|
return allEvents
|
|
.filter(function (ev) { return state.cat === 'all' || ev.category === state.cat; })
|
|
.map(function (ev) { ev._dist = distanceKm(state.source[0], state.source[1], ev.lat, ev.lon); return ev; })
|
|
.filter(function (ev) { return ev._dist <= state.rangeKm; })
|
|
.sort(function (a, b) { return a._dist - b._dist; });
|
|
}
|
|
|
|
function updateUrl() {
|
|
if (!window.history || !window.history.replaceState || !window.URL) return;
|
|
var url = new URL(window.location.href);
|
|
url.searchParams.set('lat', state.source[0].toFixed(5));
|
|
url.searchParams.set('lon', state.source[1].toFixed(5));
|
|
url.searchParams.set('range', state.rangeKm);
|
|
window.history.replaceState(null, '', url.toString());
|
|
}
|
|
|
|
function render() {
|
|
var visible = inRange();
|
|
rebuildMarkers(visible);
|
|
|
|
var legendEl = document.getElementById('legend');
|
|
if (legendEl) {
|
|
var seenCats = [];
|
|
visible.forEach(function (ev) {
|
|
if (ev.category && seenCats.indexOf(ev.category) === -1) seenCats.push(ev.category);
|
|
});
|
|
legendEl.innerHTML = seenCats.slice(0, 8).map(function (cat) {
|
|
return '<span><span class="dot" style="background:' + categoryMarkerHex(cat) + ';"></span>' + cat + '</span>';
|
|
}).join('');
|
|
}
|
|
|
|
var statusEl = document.getElementById('locateStatus');
|
|
setLocateStatus(statusEl, 'Showing events within ' + state.rangeKm + ' km', false);
|
|
|
|
var countEl = document.getElementById('resultCount');
|
|
if (countEl) countEl.textContent = visible.length + (visible.length === 1 ? ' event' : ' events');
|
|
|
|
var panelEl = document.getElementById('panelList');
|
|
if (panelEl) {
|
|
panelEl.innerHTML = visible.map(function (ev) {
|
|
var distLabel = ev._dist < 1 ? Math.round(ev._dist * 1000) : ev._dist.toFixed(1);
|
|
var distUnit = ev._dist < 1 ? 'm' : 'km';
|
|
return (
|
|
'<div class="map-row" data-id="' + ev.id + '" tabindex="0" role="button" aria-label="' + ev.title + '">' +
|
|
'<div class="dist">' + distLabel + '<span class="u">' + distUnit + '</span></div>' +
|
|
'<div><div class="name">' + ev.title + '</div><span class="when">' + (ev.venue || '') + '</span></div>' +
|
|
'<div class="go">→</div>' +
|
|
'</div>'
|
|
);
|
|
}).join('');
|
|
|
|
panelEl.querySelectorAll('.map-row').forEach(function (row) {
|
|
row.addEventListener('click', function () {
|
|
var id = row.getAttribute('data-id');
|
|
var ev = visible.filter(function (e) { return String(e.id) === String(id); })[0];
|
|
if (!ev || !map) return;
|
|
map.flyTo([ev.lat, ev.lon], 15);
|
|
var marker = markers[id];
|
|
if (marker) {
|
|
if (clusterGroup && clusterGroup.zoomToShowLayer) {
|
|
clusterGroup.zoomToShowLayer(marker, function () { marker.openPopup(); });
|
|
} else {
|
|
marker.openPopup();
|
|
}
|
|
}
|
|
highlightRow(id);
|
|
});
|
|
});
|
|
}
|
|
|
|
if (map) fitToMarkers(map, markers);
|
|
updateUrl();
|
|
}
|
|
|
|
// Moving further than the pool's own coverage (maxRangeKm around the
|
|
// server-resolved center) can't be answered from what's already
|
|
// loaded — that combination might reach past maxRangeKm even if the
|
|
// new point itself is inside it, so the check is deliberately
|
|
// conservative: reload whenever full coverage isn't guaranteed,
|
|
// rather than risk silently showing an incomplete result.
|
|
function setSource(lat, lon) {
|
|
saveLastLocation(lat, lon);
|
|
var distFromOriginal = distanceKm(originalCenter[0], originalCenter[1], lat, lon);
|
|
if (distFromOriginal + state.rangeKm > maxRangeKm) {
|
|
var url = new URL(window.location.href);
|
|
url.searchParams.set('lat', lat.toFixed(5));
|
|
url.searchParams.set('lon', lon.toFixed(5));
|
|
url.searchParams.set('range', state.rangeKm);
|
|
window.location.href = url.toString();
|
|
return;
|
|
}
|
|
|
|
state.source = [lat, lon];
|
|
if (sourceMarker) sourceMarker.setLatLng(state.source);
|
|
if (map) map.panTo(state.source);
|
|
render();
|
|
}
|
|
|
|
if (map) {
|
|
map.on('click', function (e) { manualLocationSet = true; setSource(e.latlng.lat, e.latlng.lng); });
|
|
}
|
|
if (sourceMarker) {
|
|
sourceMarker.on('dragend', function () {
|
|
manualLocationSet = true;
|
|
var ll = sourceMarker.getLatLng();
|
|
setSource(ll.lat, ll.lng);
|
|
});
|
|
}
|
|
|
|
var rangeSelect = document.getElementById('rangeSelect');
|
|
if (rangeSelect) {
|
|
rangeSelect.addEventListener('change', function () {
|
|
state.rangeKm = parseInt(rangeSelect.value, 10) || state.rangeKm;
|
|
render();
|
|
});
|
|
}
|
|
|
|
var chipsEl = document.getElementById('catChips');
|
|
if (chipsEl) {
|
|
chipsEl.addEventListener('click', function (e) {
|
|
var btn = e.target.closest('.chip-sm');
|
|
if (!btn) return;
|
|
chipsEl.querySelectorAll('.chip-sm').forEach(function (c) { c.classList.remove('is-active'); });
|
|
btn.classList.add('is-active');
|
|
state.cat = btn.getAttribute('data-cat');
|
|
render();
|
|
});
|
|
}
|
|
|
|
// Nominatim: explicit submit only, never as-you-type — required by
|
|
// its usage policy (max ~1 req/s, no autocomplete-style querying).
|
|
var locationForm = document.getElementById('locationSearchForm');
|
|
if (locationForm) {
|
|
locationForm.addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
var input = document.getElementById('locationSearch');
|
|
var query = (input.value || '').trim();
|
|
if (!query) return;
|
|
manualLocationSet = true;
|
|
var statusEl = document.getElementById('locateStatus');
|
|
setLocateStatus(statusEl, 'Looking up "' + query + '"…', false);
|
|
fetch('https://nominatim.openstreetmap.org/search?format=json&limit=1&q=' + encodeURIComponent(query))
|
|
.then(function (res) { return res.json(); })
|
|
.then(function (results) {
|
|
if (!results || !results.length) {
|
|
setLocateStatus(statusEl, 'Could not find "' + query + '"', true);
|
|
return;
|
|
}
|
|
setSource(parseFloat(results[0].lat), parseFloat(results[0].lon));
|
|
})
|
|
.catch(function () {
|
|
setLocateStatus(statusEl, 'Location search failed', true);
|
|
});
|
|
});
|
|
}
|
|
|
|
function requestLocation(isAutoCheck) {
|
|
var statusEl = document.getElementById('locateStatus');
|
|
if (!navigator.geolocation) {
|
|
setLocateStatus(statusEl, 'Location not supported by your browser', true);
|
|
return;
|
|
}
|
|
setLocateStatus(statusEl, 'Finding you…', false);
|
|
navigator.geolocation.getCurrentPosition(function (pos) {
|
|
// A manual search/click/drag may have already happened while this
|
|
// (silent, permission-check-triggered) lookup was still resolving.
|
|
if (isAutoCheck && manualLocationSet) return;
|
|
setSource(pos.coords.latitude, pos.coords.longitude);
|
|
}, function () {
|
|
setLocateStatus(statusEl, "Couldn't get your location", true);
|
|
}, { timeout: 8000 });
|
|
}
|
|
|
|
var locateBtn = document.getElementById('locateBtn');
|
|
if (locateBtn) locateBtn.addEventListener('click', function () { manualLocationSet = true; requestLocation(false); });
|
|
|
|
// An explicit ?lat=/&lon= in the URL (e.g. a shared link) always wins.
|
|
// Otherwise, a remembered search/geolocation takes priority over asking
|
|
// the browser again — restoring it counts as the user's own manual
|
|
// choice, so a slower-to-resolve auto-geolocation check below can't
|
|
// clobber it. If it's far enough from this page's own server-resolved
|
|
// center, setSource's own reload-threshold logic kicks in as usual.
|
|
var urlHasExplicitLocation = /[?&]lat=/.test(window.location.search);
|
|
var lastLocation = urlHasExplicitLocation ? null : loadLastLocation();
|
|
if (lastLocation) {
|
|
manualLocationSet = true;
|
|
setSource(lastLocation.lat, lastLocation.lon);
|
|
} else if (navigator.permissions && navigator.permissions.query) {
|
|
navigator.permissions.query({ name: 'geolocation' }).then(function (status) {
|
|
if (status.state === 'granted') requestLocation(true);
|
|
}).catch(function () {});
|
|
}
|
|
|
|
render();
|
|
|
|
return { map: map };
|
|
}
|
|
|
|
window.Vindn = window.Vindn || {};
|
|
window.Vindn.categoryColor = categoryColor;
|
|
window.Vindn.categoryMarkerHex = categoryMarkerHex;
|
|
window.Vindn.dotIcon = dotIcon;
|
|
window.Vindn.distanceKm = distanceKm;
|
|
window.Vindn.renderPinMap = renderPinMap;
|
|
window.Vindn.readEmbeddedJson = readEmbeddedJson;
|
|
window.Vindn.initMapStage = initMapStage;
|
|
window.Vindn.initRadiusMapStage = initRadiusMapStage;
|
|
})(window);
|