get current location javascript google maps

Solutions on MaxInterview for get current location javascript google maps by the best coders in the world

showing results for - "get current location javascript google maps"
Aloysius
25 Mar 2019
1// Note: This example requires that you consent to location sharing when
2// prompted by your browser. If you see the error "The Geolocation service
3// failed.", it means you probably did not give permission for the browser to
4// locate you.
5let map, infoWindow;
6
7function initMap() {
8  map = new google.maps.Map(document.getElementById("map"), {
9    center: { lat: -34.397, lng: 150.644 },
10    zoom: 6,
11  });
12  infoWindow = new google.maps.InfoWindow();
13  const locationButton = document.createElement("button");
14  locationButton.textContent = "Pan to Current Location";
15  locationButton.classList.add("custom-map-control-button");
16  map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
17  locationButton.addEventListener("click", () => {
18    // Try HTML5 geolocation.
19    if (navigator.geolocation) {
20      navigator.geolocation.getCurrentPosition(
21        (position) => {
22          const pos = {
23            lat: position.coords.latitude,
24            lng: position.coords.longitude,
25          };
26          infoWindow.setPosition(pos);
27          infoWindow.setContent("Location found.");
28          infoWindow.open(map);
29          map.setCenter(pos);
30        },
31        () => {
32          handleLocationError(true, infoWindow, map.getCenter());
33        }
34      );
35    } else {
36      // Browser doesn't support Geolocation
37      handleLocationError(false, infoWindow, map.getCenter());
38    }
39  });
40}
41
42function handleLocationError(browserHasGeolocation, infoWindow, pos) {
43  infoWindow.setPosition(pos);
44  infoWindow.setContent(
45    browserHasGeolocation
46      ? "Error: The Geolocation service failed."
47      : "Error: Your browser doesn't support geolocation."
48  );
49  infoWindow.open(map);
50}
51