From ab9198d989e0889816e510b66dad1548ce0cfb48 Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Wed, 30 Apr 2025 17:57:36 +0200 Subject: feat: add button to share current position --- script.js | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/script.js b/script.js index c998b4b..8e539d8 100644 --- a/script.js +++ b/script.js @@ -33,16 +33,15 @@ function route() { const shareInputButton = createEl('button', {}, ['Share']); const inputGroup = createEl('div', { class: 'input-group' }, [input, shareInputButton]); const errorDiv = createEl('div', { class: 'error' }); - content.append(createEl('label', {}, ['Latitude, longitude', inputGroup])); + content.append(createEl('label', {}, ['Enter latitude, longitude', inputGroup])); content.append(errorDiv); function shareInput() { if (!input.value.trim()) { return; } try { - let [lat, lon] = parseLatLon(input.value); - // TODO: use navigator.share if supported - window.location = `#${lat},${lon}`; + const [lat, lon] = parseLatLon(input.value); + shareLocation(lat, lon); } catch (error) { errorDiv.textContent = error; } @@ -53,7 +52,20 @@ function route() { } }); shareInputButton.addEventListener('click', shareInput); - // TODO: provide a button to share the current position via navigator.geolocation.getCurrentPosition if supported + if (navigator.geolocation) { + const shareCurPos = createEl('button', {}, ['Share current position']); + content.append('or ', shareCurPos, errorDiv); + shareCurPos.addEventListener('click', () => { + navigator.geolocation.getCurrentPosition( + (pos) => { + shareLocation(pos.coords.latitude, pos.coords.longitude); + }, + (err) => { + errorDiv.textContent = err.message; + }, + ); + }); + } } else { document.title = 'Open location'; @@ -71,6 +83,11 @@ function route() { } } +function shareLocation(lat, lon) { + // TODO: use navigator.share if supported + window.location = `#${lat},${lon}`; +} + function parseLatLon(text) { if (text == '') { return null; -- cgit v1.2.3