Standortbestimmung: Nutzer- oder Gerätepositionen auf Karten anzeigen
Mit Sammlungen den Überblick behalten Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Übersicht
In dieser Anleitung erfahren Sie, wie Sie den geografischen Standort eines Geräts mithilfe der HTML5-Standortbestimmung Ihres Browsers und der Maps JavaScript API auf einer Google Maps-Karte darstellen können. Der geografische Standort wird nur angezeigt, wenn der Nutzer die Standortfreigabe aktiviert hat.
Wenn der Nutzer die Anfrage zur Standortbestimmung auslöst, wird er vom Browser aufgefordert, seine Einwilligung zum Zugriff auf die Standortdaten des Geräts zu erteilen. Wenn die Anfrage fehlschlägt, kann das daran liegen, dass die Berechtigungen zur Standortermittlung abgelehnt wurden oder dass der Standort des Geräts nicht ermittelt werden konnte. Diese Funktion ist nur in sicheren Kontexten (HTTPS) in einigen oder allen unterstützten Browsern verfügbar.
Unten sehen Sie eine Karte, auf der der aktuelle Standort des Geräts des Nutzers ermittelt werden kann.
Im folgenden Beispiel wird der gesamte Code angezeigt, den Sie zum Erstellen dieser Karte benötigen.
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;
Der Begriff „Standortbestimmung“ bezieht sich auf die Ermittlung des geografischen Standorts eines Geräts über eine Vielzahl von Datenerhebungsmechanismen. Die meisten Dienste nutzen Netzwerkroutingadressen oder interne GPS-Chips zur Bestimmung des Standorts. Die Geolocation API ist gerätespezifisch. Das bedeutet, dass Browser oder Geräte die Standortbestimmung unterstützen müssen, damit sie über Webanwendungen genutzt werden kann.
W3C-Standard zur Standortbestimmung
Anwendungen, die den Standort ermitteln sollen, müssen den W3C-Standard zur Standortbestimmung unterstützen. Im Beispielcode oben wird der Standort des Geräts über die W3C-navigator.geolocation API bestimmt.
Manchmal verwenden Websites IP-Adressen, um den Standort eines Geräts zu ermitteln. Dies kann jedoch nur eine grobe Schätzung dieses Standorts liefern. W3C-Standard-APIs sind am weitesten verbreitet und am genauesten. Daher sollten sie gegenüber anderen Verfahren zur Standortbestimmung priorisiert werden.
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Benötigte Informationen nicht gefunden","missingTheInformationINeed","thumb-down"],["Zu umständlich/zu viele Schritte","tooComplicatedTooManySteps","thumb-down"],["Nicht mehr aktuell","outOfDate","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Problem mit Beispielen/Code","samplesCodeIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 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."]]