Make the map center static when map reloads

This commit is contained in:
didier committed 2025-01-19 10:54:04 -05:00
1 parent cab7eada1f
commit 79488d75e8
4 files changed
+94 -14

No files matched your search

+71 -2
View File
@@ -13,7 +13,28 @@ function findBaryCenter(points) {
return [lat / points.length, lon / points.length]
}
function getCenter(data) {
function elementSpecifyMapCenter(elm) {
return !!elm.getAttribute('data-initial-lon') && elm.getAttribute('data-initial-lat');
}
function getMapCenterFromElement(elm) {
const lon = parseFloat(elm.getAttribute('data-initial-lon'))
const lat = parseFloat(elm.getAttribute('data-initial-lat'))
return [lat, lon];
}
function elementSpecifyMapZoom(elm) {
return !!elm.getAttribute('data-initial-zoom');
}
function getMapZoomFromElement(elm) {
return parseFloat(elm.getAttribute('data-initial-zoom'))
}
function getCenter(data, elm) {
if(elementSpecifyMapCenter(elm)){
return getMapCenterFromElement(elm)
}
if (!data) {
return centerOfTheWorld;
}
@@ -49,11 +70,59 @@ function getUrl(city, date) {
return `/api/roads?${new URLSearchParams(params).toString()}`
}
function recenterURLPointsToMaps(url, center, zoom) {
url.searchParams.set('lat', center.lat);
url.searchParams.set('lon', center.lng);
url.searchParams.set('zoom', zoom);
return url;
}
function recenterLinkThatPointsToMaps(elm, center, zoom) {
const href = elm.getAttribute("href");
try {
const url = new URL(href, window.document.location.origin)
const newUrl = recenterURLPointsToMaps(url, center, zoom);
elm.setAttribute("href", newUrl.toString());
} catch (e) {
console.error(`Could not recenter ${elm} with href ${href}.`)
}
}
function recenterLinksThatPointsToMaps(center, zoom) {
const elms = document.getElementsByClassName("map-link");
for (const elm of elms) {
recenterLinkThatPointsToMaps(elm, center, zoom);
}
}
function onMapChange(e) {
const center = e.target.getCenter();
const zoom = e.target.getZoom();
recenterLinksThatPointsToMaps(center, zoom);
}
function hookEvents(map){
const events = ['zoomend', 'moveend', 'load'];
events.forEach((event) => map.on(event, onMapChange));
}
function getZoom(elm){
return elementSpecifyMapCenter(elm) ? getMapZoomFromElement(elm): 13;
}
async function renderLeafletMap(city, date) {
const resp = await fetch(getUrl(city, date));
const roads = await resp.json();
const elm = document.getElementById("leaflet-map")
const map = leaflet.map("leaflet-map").setView(getCenter(roads), 13);
const map = leaflet.map(elm);
hookEvents(map)
map.setView(getCenter(roads, elm), getZoom(elm));
leaflet
.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {maxZoom: 19})