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 2015年7月.
安全なコンテキスト用: この機能は一部またはすべての対応しているブラウザーにおいて、安全なコンテキスト (HTTPS) でのみ利用できます。
Geolocation の watchPosition() メソッドは、端末の位置が変化するたびに自動的に呼び出されるハンドラー関数を登録するために用いられます。また必要に応じてエラー処理コールバック関数を指定することができます。
構文
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> |
ブラウザーの互換性
Loading…
関連情報
- 位置情報 API の使用
- 所属するインターフェイス
Geolocationと、アクセス方法であるNavigator.geolocation。 - 反対の操作:
Geolocation.clearWatch() - 類似のメソッド:
Geolocation.getCurrentPosition()