מיקום גיאוגרפי: הצגת מיקום המשתמש או המכשיר במפות 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. שימו לב הקוד לדוגמה שלמעלה קובע את מיקום המכשיר באמצעות טופס ה-W3C API של navigator.geolocation.

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