Ubicación geográfica: cómo mostrar la posición de un usuario o un dispositivo en Maps
Organiza tus páginas con colecciones Guarda y categoriza el contenido según tus preferencias.
Descripción general
En este instructivo, se muestra cómo mostrar la ubicación geográfica de un dispositivo en un mapa de Google con la función de ubicación geográfica HTML5 de tu navegador y la API de Maps JavaScript. La ubicación geográfica solo se mostrará si el usuario permitió compartir su ubicación.
Cuando el usuario active la solicitud de ubicación geográfica, recibirá un mensaje del navegador para que otorgue su consentimiento para acceder a los datos de ubicación del dispositivo. Si la solicitud falla, es posible que se deban rechazar los permisos de ubicación o que el dispositivo no pueda determinar su ubicación. Esta función solo está disponible en contextos seguros (HTTPS), en algunos o todos los navegadores compatibles.
A continuación, se muestra un mapa que puede identificar la ubicación actual del dispositivo del usuario.
En el siguiente ejemplo, se muestra el código completo que necesitas para crear este mapa.
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 ubicación geográfica permite identificar dónde se encuentran un usuario o un dispositivo mediante diferentes mecanismos de recopilación de datos. Por lo general, la mayoría de los servicios de ubicación geográfica usan direcciones de enrutamiento de red o chips GPS internos para determinar la ubicación. La API de Geolocation es específica según el dispositivo. Esto significa que los navegadores o dispositivos deben admitir la ubicación geográfica para poder usarla a través de aplicaciones web.
Estándar de ubicación geográfica de W3C
Las aplicaciones que deseen realizar ubicaciones geográficas deben admitir el estándar de ubicación geográfica de W3C. Ten en cuenta que el código de muestra anterior determina la ubicación del dispositivo a través de la API de navigator.geolocation de W3C.
A veces, los sitios web usan direcciones IP para detectar la ubicación de un dispositivo. Sin embargo, esto solo puede proporcionar una estimación aproximada de esa ubicación. Las APIs estándar del W3C son las más admitidas y precisas, por lo que se deben priorizar ante otros métodos de ubicación geográfica.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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."]]