From 52e4ecb2a2691bab5f6cbe829fd6186d0a6cbbe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Baylac-Jacqu=C3=A9?= Date: Tue, 22 Feb 2022 17:01:34 +0100 Subject: [PATCH] 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. --- webapp/templates/app.js | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/webapp/templates/app.js b/webapp/templates/app.js index 85e3e58..b3800b0 100644 --- a/webapp/templates/app.js +++ b/webapp/templates/app.js @@ -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: '© OpenStreetMap 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);