diff --git a/README.md b/README.md index f33f173..0c4574f 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,40 @@ 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); + }); + + // .stringify() calls .toJSON() automatically + const body = JSON.stringify(position, null, 2); + + // Prepare the fetch request options + const options = { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body + }; + + // Send request + await fetch('https://example.com/api/positions', options); + } catch (error) { + console.error('Error getting or sending position data:', error); + } +} + +sendPosition(); +``` + ### More examples The specification provides [examples](https://w3c.github.io/geolocation-api/#examples) covering different use case.