Skip to content

Commit f9dafa8

Browse files
docs: show new .toJSON() capability (#151)
1 parent 27fce83 commit f9dafa8

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

README.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,40 @@ Finally, stop watching the user's location.
4444
navigator.geolocation.clearWatch(watchId);
4545
```
4646

47+
### `GeolocationPosition` as JSON
48+
49+
You can also easily treat `GeolocationPosition` objects as JSON:
50+
51+
```JS
52+
async function sendPosition() {
53+
try {
54+
// Get the current position
55+
const position = await new Promise((resolve, reject) => {
56+
navigator.geolocation.getCurrentPosition(resolve, reject);
57+
});
58+
59+
// .stringify() calls .toJSON() automatically
60+
const body = JSON.stringify(position, null, 2);
61+
62+
// Prepare the fetch request options
63+
const options = {
64+
method: 'POST',
65+
headers: {
66+
'Content-Type': 'application/json'
67+
},
68+
body
69+
};
70+
71+
// Send request
72+
await fetch('https://example.com/api/positions', options);
73+
} catch (error) {
74+
console.error('Error getting or sending position data:', error);
75+
}
76+
}
77+
78+
sendPosition();
79+
```
80+
4781
### More examples
4882

4983
The specification provides [examples](https://w3c.github.io/geolocation-api/#examples) covering different use case.

0 commit comments

Comments
 (0)