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

סקירה כללית

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

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

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

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

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