このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

GeolocationCoordinates: toJSON() メソッド

Baseline 2024
Newly available

Since September 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

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() を自動的に呼び出します。

仕様書

Specification
Geolocation
# tojson-method-0

ブラウザーの互換性

関連情報