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.

La méthode Geolocation.watchPosition() permet de manipuler une fonction appelée automatiquement à chaque fois que la position de l'appareil change. Vous pouvez de même, en option, manipuler une autre fonction appelée automatiquement pour gérer les erreurs.

Cette méthode retourne une valeur ID de veille qui permet de libérer les fonctions déclarées automatiquement, évoquées précédemment, à l'aide de la méthode Geolocation.clearWatch().

Syntaxe

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

Paramètres

success

Nom d'une fonction appelée qui a pour paramètre l'objet Position.

error Facultatif

Nom d'une fonction optionnelle qui a pour paramètre l'objet PositionError.

options Facultatif

Un objet optionnel PositionOptions.

Exemple

js
var id, target, options;

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

  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
    console.log("Bravo, vous avez atteint la cible");
    navigator.geolocation.clearWatch(id);
  }
}

function error(err) {
  console.warn("ERROR(" + err.code + "): " + err.message);
}

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

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

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

Note : Si votre application fonctionne sous Firefox OS, veillez à la geolocation wake lock pour que votre application continue à recevoir les changements de positions si votre application tourne en tâche de fond, ou si votre écran est éteint.

Spécifications

Specification
Geolocation
# watchposition-method

Compatibilité des navigateurs

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

Voir aussi