From 1b92143355851c09cebe97b5772d6883cb39f932 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20C=C3=A1ceres?= Date: Tue, 23 Apr 2024 11:07:31 +1000 Subject: [PATCH 1/3] chore: show new .toJSON() capability --- README.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/README.md b/README.md index f33f173..a8ea443 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,41 @@ Finally, stop watching the user's location. navigator.geolocation.clearWatch(watchId); ``` +### `GeolocationPosition` as JSON + +You can also easily treat `GeolocationPosition` objects as JSON: + +```JS +async function sendPosition() { + try { + // Get the current position + const position = await new Promise((resolve, reject) => { + navigator.geolocation.getCurrentPosition(resolve, reject); + }); + + // Convert to JSON text + const body = JSON.stringify(position, null, 2); + + // Prepare the fetch request options + const options = { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + // .stringify() calls .toJSON() automatically + body + }; + + // Send request + await fetch('https://example.com/api/positions', options); + } catch (error) { + console.error('Error sending position data:', error); + } +} + +sendPosition(); +``` + ### More examples The specification provides [examples](https://w3c.github.io/geolocation-api/#examples) covering different use case. From 2b887879039add4cd0b7713a5e5883c221a2b5fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20C=C3=A1ceres?= Date: Tue, 23 Apr 2024 11:09:41 +1000 Subject: [PATCH 2/3] fixed comment --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a8ea443..de6f576 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ async function sendPosition() { navigator.geolocation.getCurrentPosition(resolve, reject); }); - // Convert to JSON text + // .stringify() calls .toJSON() automatically const body = JSON.stringify(position, null, 2); // Prepare the fetch request options @@ -69,7 +69,6 @@ async function sendPosition() { headers: { 'Content-Type': 'application/json' }, - // .stringify() calls .toJSON() automatically body }; From 7840b6f5eaadd144c6aaf8893f2ff963db76404f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20C=C3=A1ceres?= Date: Wed, 1 May 2024 10:08:26 +1000 Subject: [PATCH 3/3] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index de6f576..0c4574f 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ async function sendPosition() { // Send request await fetch('https://example.com/api/positions', options); } catch (error) { - console.error('Error sending position data:', error); + console.error('Error getting or sending position data:', error); } }