webapp: save map position/zoom state in the URL search string

Doing this provides the user a way to share the result of a
eligibility test with other people by sharing the browser URL.
This commit is contained in:
Félix Baylac-Jacqué 2022-02-22 17:01:34 +01:00
parent b708c894be
commit 52e4ecb2a2

View file

@ -1,21 +1,31 @@
const minZoomForRequest = 17;
let markers = [];
function initMap(btn) {
let map = L.map('map').setView([46.710, 3.669], 6);
// Init map position/zoom. Potentially using what's in the URL search string.
const params = new URLSearchParams(window.location.search);
let x = parseFloat(params.get('x'));
let y = parseFloat(params.get('y'));
let z = parseInt(params.get('z'));
let map = L.map('map');
if(x && y && z) {
map.setView([y, x], z);
fetchEligData(map);
displayBtn(btn);
} else {
map.setView([46.710, 3.669], 6);
}
L.tileLayer('https://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
map.on("zoom", () => {
console.log(map.getZoom());
map.on("zoom", () => {
/* We only want to enable the search button when we reached a sufficient zoom level */
if (btn.disabled && map.getZoom() >= minZoomForRequest) {
btn.disabled = false;
btn.title = "Rechercher les données d'éligibilité pour cette zone."
displayBtn(btn);
}
if (!btn.disabled && map.getZoom() < minZoomForRequest) {
btn.disabled = true;
btn.title = "Veuillez zoomer plus la carte avant de lancer une recherche d'éligibilité.";
hideBtn(btn);
}
});
return map;
@ -68,6 +78,11 @@ function updateEligData(map, eligData) {
});
}
function updateUrl(map) {
const c = map.getCenter();
history.replaceState({}, "", encodeURI(`?x=${c.lng}&y=${c.lat}&z=${map.getZoom()}`));
}
async function fetchEligData(map) {
const zoom = map.getZoom();
if (zoom >= minZoomForRequest) {
@ -78,6 +93,7 @@ async function fetchEligData(map) {
const source = await fetch(reqUri);
const eligData = await source.json();
updateEligData(map, eligData);
updateUrl(map);
}
}
@ -89,6 +105,17 @@ function initBtn() {
return btn;
}
function displayBtn(btn) {
btn.disabled = false;
btn.title = "Rechercher les données d'éligibilité pour cette zone."
}
function hideBtn(btn) {
btn.disabled = true;
btn.title = "Veuillez zoomer plus la carte avant de lancer une recherche d'éligibilité.";
}
const btn = initBtn();
const map = initMap(btn);
const addrSearch = initAddrSearch(map);