GeolocationCoordinates: toJSON() 方法

Baseline 2024
新推出

自 2024 年 9 月起,此功能已可在最新设备和浏览器版本上使用。此功能可能无法在旧设备或浏览器上使用。

toJSON() 方法是 GeolocationCoordinates 接口的一个 序列化器;它返回 GeolocationCoordinates 对象的 JSON 表示。

语法

js
toJSON()

参数

无。

返回值

一个 JSON 对象,它是 GeolocationCoordinates 对象的序列化结果。

示例

使用 toJSON() 方法

在此示例中,调用 position.coords.toJSON() 会返回 GeolocationCoordinates 对象的 JSON 表示。

js
navigator.geolocation.getCurrentPosition((position) => {
  console.log(position.coords.toJSON());
});

这将记录一个类似如下的 JSON 对象

json
{
  "accuracy": 12.0,
  "latitude": 53.0,
  "longitude": 8.0,
  "altitude": null,
  "altitudeAccuracy": null,
  "heading": null,
  "speed": null
}

要获取 JSON 字符串,你可以直接使用 JSON.stringify(position.coords);它会自动调用 toJSON()

规范

规范
Geolocation
# tojson-method-0

浏览器兼容性

另见