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

瀏覽器相容性

另見