Géolocalisation : afficher la position d'un utilisateur ou d'un appareil sur Maps
Restez organisé à l'aide des collections Enregistrez et classez les contenus selon vos préférences.
Présentation
Ce tutoriel explique comment afficher l'emplacement géographique d'un appareil sur une carte Google en utilisant la fonctionnalité HTML5 Geolocation de votre navigateur ainsi que l'API Maps JavaScript. L'emplacement géographique ne s'affiche que si l'utilisateur a autorisé le partage de position.
Lorsque l'utilisateur déclenche la requête de géolocalisation, il reçoit une invite du navigateur lui demandant d'autoriser l'accès aux données de localisation de l'appareil. Si la requête échoue, cela peut être dû au fait que les autorisations d'accéder à la position ont été refusées ou que l'appareil n'a pas pu déterminer sa position. Cette fonctionnalité n'est disponible que dans les contextes sécurisés (HTTPS), dans certains ou tous les navigateurs compatibles.
La carte ci-dessous permet d'identifier la position actuelle de l'appareil de l'utilisateur.
L'exemple ci-dessous montre tout le code dont vous avez besoin pour créer cette carte.
TypeScript
// Note: This example requires that you consent to location sharing when// prompted by your browser. If you see the error "The Geolocation service// failed.", it means you probably did not give permission for the browser to// locate you.letmap:google.maps.Map,infoWindow:google.maps.InfoWindow;functioninitMap():void{map=newgoogle.maps.Map(document.getElementById("map")asHTMLElement,{center:{lat:-34.397,lng:150.644},zoom:6,});infoWindow=newgoogle.maps.InfoWindow();constlocationButton=document.createElement("button");locationButton.textContent="Pan to Current Location";locationButton.classList.add("custom-map-control-button");map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);locationButton.addEventListener("click",()=>{// Try HTML5 geolocation.if(navigator.geolocation){navigator.geolocation.getCurrentPosition((position:GeolocationPosition)=>{constpos={lat:position.coords.latitude,lng:position.coords.longitude,};infoWindow.setPosition(pos);infoWindow.setContent("Location found.");infoWindow.open(map);map.setCenter(pos);},()=>{handleLocationError(true,infoWindow,map.getCenter()!);});}else{// Browser doesn't support GeolocationhandleLocationError(false,infoWindow,map.getCenter()!);}});}functionhandleLocationError(browserHasGeolocation:boolean,infoWindow:google.maps.InfoWindow,pos:google.maps.LatLng){infoWindow.setPosition(pos);infoWindow.setContent(browserHasGeolocation?"Error: The Geolocation service failed.":"Error: Your browser doesn't support geolocation.");infoWindow.open(map);}declareglobal{interfaceWindow{initMap:()=>void;}}window.initMap=initMap;
// Note: This example requires that you consent to location sharing when// prompted by your browser. If you see the error "The Geolocation service// failed.", it means you probably did not give permission for the browser to// locate you.letmap,infoWindow;functioninitMap(){map=newgoogle.maps.Map(document.getElementById("map"),{center:{lat:-34.397,lng:150.644},zoom:6,});infoWindow=newgoogle.maps.InfoWindow();constlocationButton=document.createElement("button");locationButton.textContent="Pan to Current Location";locationButton.classList.add("custom-map-control-button");map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);locationButton.addEventListener("click",()=>{// Try HTML5 geolocation.if(navigator.geolocation){navigator.geolocation.getCurrentPosition((position)=>{constpos={lat:position.coords.latitude,lng:position.coords.longitude,};infoWindow.setPosition(pos);infoWindow.setContent("Location found.");infoWindow.open(map);map.setCenter(pos);},()=>{handleLocationError(true,infoWindow,map.getCenter());},);}else{// Browser doesn't support GeolocationhandleLocationError(false,infoWindow,map.getCenter());}});}functionhandleLocationError(browserHasGeolocation,infoWindow,pos){infoWindow.setPosition(pos);infoWindow.setContent(browserHasGeolocation?"Error: The Geolocation service failed.":"Error: Your browser doesn't support geolocation.",);infoWindow.open(map);}window.initMap=initMap;
La géolocalisation consiste à identifier l'emplacement géographique d'un appareil informatique à l'aide de divers mécanismes de collecte de données. La plupart des services de géolocalisation s'appuient sur des adresses d'acheminement réseau ou des puces GPS internes pour déterminer cette position. L'API de géolocalisation est spécifique à chaque appareil. En d'autres termes, les navigateurs et appareils doivent être compatibles avec la géolocalisation pour pouvoir l'utiliser dans les applications Web.
Norme de géolocalisation W3C
Les applications qui souhaitent utiliser la géolocalisation doivent respecter la norme de géolocalisation W3C. Notez que l'exemple de code ci-dessus détermine l'emplacement de l'appareil via l'API navigator.geolocation du W3C.
Les sites Web utilisent parfois des adresses IP pour détecter la position d'un appareil. Toutefois, cette méthode ne fournit qu'une estimation approximative de cette position. Les API conformes aux normes du W3C sont les plus acceptées et les plus précises. C'est donc la méthode de géolocalisation à privilégier.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/06 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/08/06 (UTC)."],[[["\u003cp\u003eThis tutorial demonstrates how to pinpoint a device's location on a Google map using HTML5 Geolocation and the Maps JavaScript API, contingent on user permission for location sharing.\u003c/p\u003e\n"],["\u003cp\u003eThe provided code samples (TypeScript and JavaScript) showcase the implementation of this functionality, including error handling for cases where location services are unavailable or denied.\u003c/p\u003e\n"],["\u003cp\u003eGeolocation, the process of identifying a device's geographical position, is achieved through various methods, with W3C-standard APIs offering the highest accuracy and support.\u003c/p\u003e\n"],["\u003cp\u003eUser consent is paramount; the browser prompts users to grant permission for accessing location data, and the map only displays the location if this permission is granted.\u003c/p\u003e\n"],["\u003cp\u003eThe tutorial emphasizes using the W3C Geolocation standard (\u003ccode\u003enavigator.geolocation\u003c/code\u003e API) for optimal accuracy and compatibility, prioritizing it over less precise IP-based location detection.\u003c/p\u003e\n"]]],["This tutorial details displaying a device's location on a Google Map using HTML5 Geolocation and the Maps JavaScript API. Users click a button, triggering a browser prompt for location sharing consent. Upon approval, `navigator.geolocation.getCurrentPosition` obtains coordinates, centers the map, and displays a \"Location found\" message. If denied or unavailable, an error message is shown. The process requires HTTPS and utilizes the W3C Geolocation standard for accurate positioning.\n"],null,["Overview\n\nThis tutorial shows you how to display the geographic location of a device on a Google map, using\nyour browser's HTML5 Geolocation feature along with the Maps JavaScript API. The\ngeographic location will only display if the user has allowed location sharing.\n\nWhen the user triggers the geolocation request, they will receive a prompt from the browser\nfor consent to access the device's location data. If the request fails, it could be because\nlocation permissions were denied, or because the device couldn't determine its location.\nThis feature is available only in secure contexts (HTTPS), in some or all supporting browsers.\n\nBelow is a map that can identify the present location of the user's device.\n\nThe sample below shows the entire code you need to create this map. \n\nTypeScript \n\n```typescript\n// Note: This example requires that you consent to location sharing when\n// prompted by your browser. If you see the error \"The Geolocation service\n// failed.\", it means you probably did not give permission for the browser to\n// locate you.\nlet map: google.maps.Map, infoWindow: google.maps.InfoWindow;\n\nfunction initMap(): void {\n map = new google.maps.Map(document.getElementById(\"map\") as HTMLElement, {\n center: { lat: -34.397, lng: 150.644 },\n zoom: 6,\n });\n infoWindow = new google.maps.InfoWindow();\n\n const locationButton = document.createElement(\"button\");\n\n locationButton.textContent = \"Pan to Current Location\";\n locationButton.classList.add(\"custom-map-control-button\");\n\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);\n\n locationButton.addEventListener(\"click\", () =\u003e {\n // Try HTML5 geolocation.\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(\n (position: GeolocationPosition) =\u003e {\n const pos = {\n lat: position.coords.latitude,\n lng: position.coords.longitude,\n };\n\n infoWindow.setPosition(pos);\n infoWindow.setContent(\"Location found.\");\n infoWindow.open(map);\n map.setCenter(pos);\n },\n () =\u003e {\n handleLocationError(true, infoWindow, map.getCenter()!);\n }\n );\n } else {\n // Browser doesn't support Geolocation\n handleLocationError(false, infoWindow, map.getCenter()!);\n }\n });\n}\n\nfunction handleLocationError(\n browserHasGeolocation: boolean,\n infoWindow: google.maps.InfoWindow,\n pos: google.maps.LatLng\n) {\n infoWindow.setPosition(pos);\n infoWindow.setContent(\n browserHasGeolocation\n ? \"Error: The Geolocation service failed.\"\n : \"Error: Your browser doesn't support geolocation.\"\n );\n infoWindow.open(map);\n}\n\ndeclare global {\n interface Window {\n initMap: () =\u003e void;\n }\n}\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/map-geolocation/index.ts#L8-L73\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\n// Note: This example requires that you consent to location sharing when\n// prompted by your browser. If you see the error \"The Geolocation service\n// failed.\", it means you probably did not give permission for the browser to\n// locate you.\nlet map, infoWindow;\n\nfunction initMap() {\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: -34.397, lng: 150.644 },\n zoom: 6,\n });\n infoWindow = new google.maps.InfoWindow();\n\n const locationButton = document.createElement(\"button\");\n\n locationButton.textContent = \"Pan to Current Location\";\n locationButton.classList.add(\"custom-map-control-button\");\n map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);\n locationButton.addEventListener(\"click\", () =\u003e {\n // Try HTML5 geolocation.\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(\n (position) =\u003e {\n const pos = {\n lat: position.coords.latitude,\n lng: position.coords.longitude,\n };\n\n infoWindow.setPosition(pos);\n infoWindow.setContent(\"Location found.\");\n infoWindow.open(map);\n map.setCenter(pos);\n },\n () =\u003e {\n handleLocationError(true, infoWindow, map.getCenter());\n },\n );\n } else {\n // Browser doesn't support Geolocation\n handleLocationError(false, infoWindow, map.getCenter());\n }\n });\n}\n\nfunction handleLocationError(browserHasGeolocation, infoWindow, pos) {\n infoWindow.setPosition(pos);\n infoWindow.setContent(\n browserHasGeolocation\n ? \"Error: The Geolocation service failed.\"\n : \"Error: Your browser doesn't support geolocation.\",\n );\n infoWindow.open(map);\n}\n\nwindow.initMap = initMap;https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/map-geolocation/docs/index.js#L7-L61\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n[View example](/maps/documentation/javascript/examples/map-geolocation)\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/map-geolocation/jsfiddle) [Google Cloud Shell](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgooglemaps%2Fjs-samples&cloudshell_git_branch=sample-map-geolocation&cloudshell_tutorial=cloud_shell_instructions.md&cloudshell_workspace=.)\n\nWhat is Geolocation?\n\nGeolocation refers to the identification of the geographic location of a computing device\nusing a variety of data collection mechanisms. Typically, most geolocation services use network\nrouting addresses or internal GPS chips to determine this location. Geolocation is a\ndevice-specific API. This means that browsers or devices must support geolocation in order to use\nit through web applications.\n\nW3C Geolocation standard\n\nApplications that want to perform geolocation must support the\n[W3C Geolocation standard](http://dev.w3.org/geo/api/spec-source.html). Notice that the\nsample code above determines the device's location through the W3C\n`navigator.geolocation` API.\n\nSometimes websites use IP addresses to detect the location of a device, however this may only provide a\nrough estimate of that location. W3C-standard APIs are the most fully-supported and most accurate, so they should be\nprioritized over other geolocation methods."]]