File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change @@ -44,6 +44,40 @@ Finally, stop watching the user's location.
4444navigator .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
4983The specification provides [ examples] ( https://w3c.github.io/geolocation-api/#examples ) covering different use case.
You can’t perform that action at this time.
0 commit comments