Geolocation: watchPosition() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

安全なコンテキスト用: この機能は一部またはすべての対応しているブラウザーにおいて、安全なコンテキスト (HTTPS) でのみ利用できます。

GeolocationwatchPosition() メソッドは、端末の位置が変化するたびに自動的に呼び出されるハンドラー関数を登録するために用いられます。また必要に応じてエラー処理コールバック関数を指定することができます。

構文

js
watchPosition(success)
watchPosition(success, error)
watchPosition(success, error, options)

引数

success

コールバック関数で、 GeolocationPosition オブジェクトを入力引数として受け取るものです。

error 省略可

任意のコールバック関数で、 GeolocationPositionError オブジェクトを入力引数として受け取るものです。

options 省略可

任意のオブジェクトで、位置を監視する構成オプションを提供します。 利用可能なオプションについての詳細は Geolocation.getCurrentPosition() を参照してください。

返値

登録されたハンドラーを識別する ID を返します。この ID を Geolocation.clearWatch() メソッドに渡してハンドラーの登録を解除することができます。

js
let id;
let target;
let options;

function success(pos) {
  const crd = pos.coords;

  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
    console.log("Congratulations, you reached the target");
    navigator.geolocation.clearWatch(id);
  }
}

function error(err) {
  console.error(`ERROR(${err.code}): ${err.message}`);
}

target = {
  latitude: 0,
  longitude: 0,
};

options = {
  enableHighAccuracy: false,
  timeout: 5000,
  maximumAge: 0,
};

id = navigator.geolocation.watchPosition(success, error, options);

仕様書

Specification
Geolocation
# watchposition-method

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
watchPosition

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報