L'API HTML Geolocation est utilisée pour obtenir la position géographique d'un utilisateur.
Étant donné que cela peut compromettre la confidentialité, le poste n'est disponible que si l'utilisateur l'approuve.
<script> let x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition,showError); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { let lat=position.coords.latitude; let lon=position.coords.longitude; let latlon=new google.maps.LatLng(lat, lon) let mapholder=document.getElementById('mapholder') mapholder.style.height='250px'; mapholder.style.width='100%'; let myOptions={ center:latlon,zoom:14, mapTypeId:google.maps.MapTypeId.ROADMAP, mapTypeControl:false, navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL} }; let map=new google.maps.Map(document.getElementById("mapholder"),myOptions); let marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"}); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } }La géolocalisation est plus précise pour les appareils dotés d'un GPS, comme les smartphones.
L'API de géolocalisation est prise en charge dans tous les navigateurs :
| Yes | Yes | Yes | Yes | Yes |
L'API de géolocalisation ne fonctionnera que sur des contextes sécurisés tels que comme HTTPS.
Si votre site est hébergé sur une origine non sécurisée (telle que HTTP) le les demandes pour obtenir la localisation des utilisateurs ne fonctionneront plus.
La méthode getCurrentPosition() est utilisée pour renvoyer la position de l'utilisateur.
L'exemple ci-dessous renvoie la latitude et la longitude de la position de l'utilisateur :
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Exemple expliqué :
Vérifiez si la géolocalisation est prise en charge
Si pris en charge, exécutez la méthode getCurrentPosition(). Sinon, afficher un message à l'utilisateur
Si la méthode getCurrentPosition() réussit, elle renvoie un objet coordonnées à la fonction spécifiée dans le paramètre (showPosition)
La fonction showPosition() affiche la latitude et la longitude
L'exemple ci-dessus est un script de géolocalisation très basique, sans gestion des erreurs.
Le deuxième paramètre de la méthode getCurrentPosition() est utilisé pour gérer les erreurs. Il spécifie une fonction à exécuter si elle ne parvient pas à obtenir l'emplacement de l'utilisateur :
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
Pour afficher le résultat sur une carte, vous devez accéder à un service de cartographie, comme Google Plans.
Dans l'exemple ci-dessous, la latitude et la longitude renvoyées sont utilisées pour afficher l'emplacement dans un Google Carte (en utilisant une image statique) :
function showPosition(position) {
let latlon = position.coords.latitude + "," + position.coords.longitude;
let img_url = "https://maps.googleapis.com/maps/api/staticmap?center=
"+latlon+"&zoom=14&size=400x300&sensor=false&key=YOUR_KEY";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}Essayez-le vous-même
<!DOCTYPE html>
<html>
<body>
<h1>HTML Geolocation</h1>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
let latlon = position.coords.latitude + "," + position.coords.longitude;
let img_url = "https://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
//To use this code on your website, get a free API key from Google.
//Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
Comment afficher une carte Google interactive avec des options de marqueur, de zoom et de glisser.
Script de carte Google
<!DOCTYPE html>
<html>
<body>
<h1>HTML Geolocation</h1>
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script src="https://maps.google.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
const latlon = new google.maps.LatLng(lat, lon)
const mapholder = document.getElementById('mapholder')
mapholder.style.height = '250px';
mapholder.style.width = '500px';
var myOptions = {
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
}
const map = new google.maps.Map(document.getElementById("mapholder"), myOptions);
const marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
Cette page a montré comment afficher la position d'un utilisateur sur une carte.
La géolocalisation est également très utile pour les informations spécifiques à un emplacement, comme :
Informations locales à jour
Affichage des points d'intérêt à proximité de l'utilisateur
Navigation étape par étape (GPS)
La méthode getCurrentPosition() renvoie un objet en cas de succès. La latitude, les propriétés de longitude et de précision sont toujours renvoyées. Les autres propriétés sont renvoyées si disponible:
La latitude sous forme de nombre décimal (toujours renvoyé)
La longitude sous forme de nombre décimal (toujours renvoyé)
La précision de la position (toujours renvoyée)
L'altitude en mètres au-dessus du niveau moyen de la mer (renvoyée si disponible)
La précision de l'altitude de la position (renvoyée si disponible)
Le cap en degrés dans le sens des aiguilles d'une montre à partir du nord (renvoyé si disponible)
La vitesse en mètres par seconde (renvoyée si disponible)
La date/heure de la réponse (renvoyée si disponible)
L'objet Géolocalisation possède également d'autres méthodes intéressantes :
watchPosition() - Renvoie la position actuelle de l'utilisateur et continue à renvoie la position mise à jour lorsque l'utilisateur se déplace (comme le GPS dans une voiture).
clearWatch() - Arrête la méthode watchPosition().
L'exemple ci-dessous montre la méthode watchPosition(). Vous avez besoin d'un appareil GPS précis pour tester cela (comme téléphone intelligent):
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>Essayez-le vous-même →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Geolocation API</h2>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
const x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>