A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developers.google.com/maps/documentation/javascript/geolocation below:

Geolocation: Displaying User or Device Position on Maps | Maps JavaScript API

Skip to main content 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.
let map: google.maps.Map, infoWindow: google.maps.InfoWindow;

function initMap(): void {
  map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 6,
  });
  infoWindow = new google.maps.InfoWindow();

  const locationButton = 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) => {
          const pos = {
            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 Geolocation
      handleLocationError(false, infoWindow, map.getCenter()!);
    }
  });
}

function handleLocationError(
  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);
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;
Note: Read the guide on using TypeScript and Google Maps. JavaScript
// 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.
let map, infoWindow;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 6,
  });
  infoWindow = new google.maps.InfoWindow();

  const locationButton = 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) => {
          const pos = {
            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 Geolocation
      handleLocationError(false, infoWindow, map.getCenter());
    }
  });
}

function handleLocationError(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;
Note: The JavaScript is compiled from the TypeScript snippet. View example Try Sample What is Geolocation?

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.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-08-14 UTC.

[[["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-14 UTC."],[[["This 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."],["The provided code samples (TypeScript and JavaScript) showcase the implementation of this functionality, including error handling for cases where location services are unavailable or denied."],["Geolocation, the process of identifying a device's geographical position, is achieved through various methods, with W3C-standard APIs offering the highest accuracy and support."],["User 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."],["The tutorial emphasizes using the W3C Geolocation standard (`navigator.geolocation` API) for optimal accuracy and compatibility, prioritizing it over less precise IP-based location detection."]]],["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"]]


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4