מיקום גיאוגרפי: הצגת מיקום המשתמש או המכשיר במפות 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 כדי לקבוע את המיקום הזה. Geolocation הוא API ספציפי למכשיר. המשמעות היא שהדפדפנים או המכשירים חייבים לתמוך במיקום גיאוגרפי כדי להשתמש בו דרך אפליקציות אינטרנט.

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

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

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