Geolocation: Displaying User or Device Position on Maps
Stay organized with collections Save and categorize content based on your preferences.
Overview
This tutorial shows you how to display the geographic location of a device on a Google map, using your browser's HTML5 Geolocation feature along with the Maps JavaScript API. The geographic location will only display if the user has allowed location sharing.
When the user triggers the geolocation request, they will receive a prompt from the browser for consent to access the device's location data. If the request fails, it could be because location permissions were denied, or because the device couldn't determine its location. This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Below is a map that can identify the present location of the user's device.
The sample below shows the entire code you need to create this map.
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;
Geolocation refers to the identification of the geographic location of a computing device using a variety of data collection mechanisms. Typically, most geolocation services use network routing addresses or internal GPS chips to determine this location. Geolocation is a device-specific API. This means that browsers or devices must support geolocation in order to use it through web applications.
W3C Geolocation standard
Applications that want to perform geolocation must support the W3C Geolocation standard. Notice that the sample code above determines the device's location through the W3C navigator.geolocation API.
Sometimes websites use IP addresses to detect the location of a device, however this may only provide a rough estimate of that location. W3C-standard APIs are the most fully-supported and most accurate, so they should be prioritized over other geolocation methods.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-20 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."]]