HTML5 - Geolocation - watchPosition() & clearWatch()
by leeroy
JavaScript
var geoLoc;
var watchID = false;
$(document).ready(function() {
// Si la géolocalisation est possible, on affiche les boutons d'action
if(navigator.geolocation)
{
geoLoc = navigator.geolocation;
$('body').append('<a href="#" id="action"></a><ul id="locations"></ul>');
$('#action').text('Démarrer la géolocalisation').click(startGeolocation);
}
else
{
$('body').append('La geolocalisation n\'est malheureusement pas prise en charge par votre navigateur.');
}
});
// Fonction qui démarre la géolocalisation
function startGeolocation()
{
watchID = geoLoc.watchPosition(showLocation, errorHandler);
// On modifier le bouton "Démarrer" en bouton "Arrêter"
$('#action').text('Arrêter la géolocalisation').click(stopGeolocation);
return false;
}
// Fonction qui arrête la géolocalisation
function stopGeolocation()
{
geoLoc.clearWatch(watchID);
watchID = false;
// On modifier le bouton "Arrêter" en bouton "Démarrer"
$('#action').text('Démarrer la géolocalisation').click(startGeolocation);
return false;
}
// Affiche la nouvelle position trouvée
function showLocation(position)
{
$('#locations').append('<li>Latitude : '+ position.coords.latitude +' - Longitude : '+ position.coords.latitude +'</li>');
}
// Gestion des erreurs, affichage d'un message à l'utilisateur.
function errorHandler(error)
{
// On log l'erreur sans l'afficher, permet simplement de débugger.
console.log('Geolocation error : code '+ error.code +' - '+ error.message);
// Affichage d'un message d'erreur plus "user friendly" pour l'utilisateur.
alert('Une erreur est survenue durant la géolocalisation. Veuillez réessayer plus tard ou contacter le support.');
}