מיקום גיאוגרפי: הצגת מיקום המשתמש או המכשיר במפות Google

סקירה

מדריך זה מראה כיצד להציג את המיקום הגיאוגרפי של מכשיר במפת Google, באמצעות תכונת המיקום הגיאוגרפי ב-HTML5 של הדפדפן יחד עם ממשק ה-API של JavaScript במפות Google. המיקום הגיאוגרפי יוצג רק אם המשתמש אפשר לשתף את המיקום.

כשהמשתמש יפעיל את בקשת המיקום הגיאוגרפי, הוא יקבל מהדפדפן בקשה להסכמה לגשת לנתוני המיקום של המכשיר. אם הבקשה נכשלת, יכול להיות שהרשאות המיקום נדחו או שהמכשיר לא הצליח לקבוע את המיקום שלו. התכונה הזו זמינה רק בהקשרים מאובטחים (HTTPS), בחלק מהדפדפנים או בכולם.

בהמשך מופיעה מפה שיכולה לזהות את המיקום הנוכחי של המכשיר של המשתמש.

הדוגמה הבאה מציגה את הקוד המלא שנדרש כדי ליצור את המפה הזו.

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;
להצגת דוגמה

רוצה לנסות את הדוגמה

מהו מיקום גיאוגרפי?

מיקום גיאוגרפי מתייחס לזיהוי המיקום הגיאוגרפי של מכשיר מחשוב באמצעות מגוון מנגנוני איסוף נתונים. בדרך כלל, רוב שירותי המיקום הגיאוגרפי משתמשים בכתובות לניתוב רשת או בצ'יפים פנימיים של GPS כדי לקבוע את המיקום הזה. המיקום הגיאוגרפי הוא API למכשיר ספציפי. כלומר, דפדפנים או מכשירים חייבים לתמוך במיקום גיאוגרפי כדי להשתמש במיקום באפליקציות אינטרנט.

תקן מיקום גיאוגרפי של W3C

אפליקציות שרוצות לבצע מיקום גיאוגרפי חייבות לתמוך בתקן W3C Geolocation. שימו לב שהקוד לדוגמה שלמעלה קובע את מיקום המכשיר באמצעות API navigator.geolocation של W3C.

לפעמים אתרים משתמשים בכתובות IP כדי לזהות את המיקום של מכשיר, אבל זו רק הערכה גסה של המיקום. ממשקי API בתקן W3C הם בעלי התמיכה המלאה והמדויקים ביותר, לכן צריך לתת להם עדיפות על פני שיטות אחרות של מיקום גיאוגרפי.