Coğrafi Konum: Haritalar'da Kullanıcının veya Cihazın Konumunu Görüntüleme

Genel Bakış

Bu eğitim, bir cihazın coğrafi konumunu Google haritasında Maps JavaScript API ile birlikte tarayıcınızın HTML5 Coğrafi Konum özelliği. İlgili içeriği oluşturmak için kullanılan coğrafi konum yalnızca kullanıcı konum paylaşımına izin verdiyse görüntülenir.

Kullanıcı coğrafi konum isteğini tetiklediğinde tarayıcıdan bir istem alır adresine gidin. İstek başarısız olursa bunun nedeni aşağıdakilerden biri olabilir: konum izinleri reddedildiği veya cihazın konumunu belirleyemediği için. Bu özellik, destekleyen tarayıcıların bazılarında veya tümünde yalnızca güvenli bağlamlarda (HTTPS) kullanılabilir.

Aşağıda, kullanıcının cihazının mevcut konumunu belirleyebilen bir harita verilmiştir.

Aşağıdaki örnekte, bu haritayı oluşturmak için ihtiyacınız olan kodun tamamı gösterilmektedir.

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;
.

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;
.
Örneği inceleyin

Örneği Deneyin

Coğrafi Konum nedir?

Coğrafi konum, bir bilgi işlem cihazının coğrafi konumunun belirlenmesini ifade eder çeşitli veri toplama mekanizmaları kullanarak. Genellikle coğrafi konum hizmetlerinin çoğu yönlendirme adreslerini veya dahili GPS çiplerini kullanır. Coğrafi konum API'yi kullanabilirsiniz. Bu, Google Haritalar'ı kullanabilmek için tarayıcıların veya cihazların coğrafi konumu desteklemesi web uygulamaları üzerinden sağlıyor.

W3C Coğrafi konum standardı

Coğrafi konum bilgisi vermek isteyen uygulamalar, W3C Coğrafi konum standardı. Not: yukarıdaki örnek kod, W3C aracılığıyla cihazın konumunu belirler navigator.geolocation API.

Bazen web siteleri bir cihazın konumunu algılamak için IP adreslerini kullanır. Ancak bu yalnızca bir yaklaşık olarak belirir. W3C standardı API'ler en tam olarak desteklenen ve en doğrudur. Bu nedenle diğer coğrafi konum yöntemlerine göre daha önceliklidir.