הוספת מפה של Google עם סמן באמצעות JavaScript

מבוא

המדריך הזה מראה איך להוסיף לאינטרנט מפת Google פשוטה עם סמן הדף הזה. הוא מתאים לאנשים בעלי ידע מתחילים או בינוני ב-HTML וב-CSS, וקצת ידע ב-JavaScript.

בהמשך מוצגת המפה שתיצרו באמצעות המדריך הזה. הסמן ממוקם ב- אולורו (נקרא גם איירס רוק) הפארק הלאומי אולורו-קאטה ג'וטה.

תחילת העבודה

יש שלושה שלבים ליצירת מפת Google באמצעות סמן בדף האינטרנט:

  1. קבלת מפתח API
  2. יצירת דף HTML
  3. הוספת מפה עם סמן

צריך דפדפן אינטרנט. כדאי לבחור דפדפן ידוע כמו Google Chrome (מומלץ), Firefox, Safari או Edge, בהתאם לפלטפורמה שלך רשימת הדפדפנים הנתמכים

שלב 1: קבלת מפתח API

בקטע הזה מוסבר איך לאמת את האפליקציה כדי Maps JavaScript API באמצעות מפתח API משלכם.

כך מקבלים מפתח API:

  1. נכנסים אל מסוף Google Cloud.

  2. יוצרים או בוחרים פרויקט.

  3. לוחצים על המשך כדי להפעיל את ה-API ואת השירותים הקשורים.

  4. בדף Credentials מקבלים API key (ומגדירים את מפתח ה-API) ). הערה: אם יש לך מפתח API בלתי מוגבל, או מפתח עם הגבלות על הדפדפן, תוכלו להשתמש במפתח הזה.

  5. כדי למנוע גניבת מכסות ולאבטח את מפתח ה-API: שימוש במפתחות API.

  6. הפעלת החיוב. למידע על שימוש וחיוב אפשר לקבל מידע נוסף.

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

    <script>
      (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
        key: "YOUR_API_KEY",
        v: "weekly",
        // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
        // Add other bootstrap parameters as needed, using camel case.
      });
    </script>
    
    style="height: 400px"

שלב 2: יוצרים דף HTML

זהו הקוד של דף אינטרנט בסיסי בפורמט HTML:

<!doctype html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script>
  </body>
</html>

חשוב לשים לב שזהו דף בסיסי מאוד עם כותרת ברמה שלוש (h3) וכותרת רכיב div יחיד. תוכלו להוסיף לדף האינטרנט כל תוכן שתרצו.

הסבר על הקוד

הקוד שבהמשך יוצר דף HTML שמכיל ראש וגוף.

<html>
 <head>
 </head>
 <body>
 </body>
</html>

אפשר להוסיף כותרת ברמה 3 מעל המפה באמצעות הקוד הבא.

<h3>My Google Maps Demo</h3>

הקוד הבא מגדיר אזור בדף עבור מפת Google שלך.

<!--The div element for the map -->
<div id="map"></div>

בשלב הזה של המדריך, השדה div מופיע רק בתור בלוק אפור, כי עדיין לא הוספת מפה. הקוד הבא מתאר את שירות ה-CSS שמגדיר את הגודל והצבע של div.

/* Set the size of the div element that contains the map */
#map {
    height: 400px; /* The height is 400 pixels */
    width: 100%; /* The width is the width of the web page */
}

בקוד שלמעלה, הרכיב style קובע את הגודל של div למפה. מגדירים את כדי שהמפה תהיה גלויה, הרוחב והגובה של div יהיו גדולים מ-0 פיקסלים. כאן גודל האותיות, div מוגדר בגובה של 400 פיקסלים וברוחב של 100% להצגה לכל רוחב דף האינטרנט.

תוכנת ה-Bootstrap מכינה את Maps JavaScript API לטעינה (לא נטענו ספריות עד לקריאה ל-importLibrary()).

<script>
  (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
    key: "YOUR_API_KEY",
    v: "weekly",
    // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
    // Add other bootstrap parameters as needed, using camel case.
  });
</script>

להוראות על קבלת מפתח API, ראו שלב 3: קבלת מפתח API מפתח API משלכם.

שלב 3: הוספת מפה עם סמן

בקטע הזה מוסבר איך לטעון את Maps JavaScript API ואיך לכתוב JavaScript משלכם שמשתמש ב-API כדי להוסיף מפה עם עט סימון.

TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

בקוד שלמעלה, הספריות Map ו-AdvancedMarkerView נטענות הפונקציה initMap() נקראת.

הסבר על הקוד

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

TypeScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };

// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

// The map, centered at Uluru
map = new Map(
  document.getElementById('map') as HTMLElement,
  {
    zoom: 4,
    center: position,
    mapId: 'DEMO_MAP_ID',
  }
);

JavaScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };
// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

// The map, centered at Uluru
map = new Map(document.getElementById("map"), {
  zoom: 4,
  center: position,
  mapId: "DEMO_MAP_ID",
});

בקוד שלמעלה, new Map() יוצר אובייקט חדש של מפות Google. המאפיין center מציין ל-API איפה למרכז את המפה.

למידע נוסף על קבלת קואורדינטות של קו אורך/רוחב, או להמיר כתובת לקואורדינטות גיאוגרפיות.

המאפיין zoom מציין את רמת המרחק מהתצוגה במפה. המרחק מהתצוגה: 0 הוא הנמוך ביותר את מרחק התצוגה, ותציג את כדור הארץ כולו. הגדירו את ערך הזום הגבוה יותר כדי להתקרב Google Earth ברזולוציה גבוהה יותר.

הקוד שבהמשך מציב סמן במפה. המאפיין position מגדיר את מיקום הסמן.

TypeScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerElement({
  map: map,
  position: position,
  title: 'Uluru'
});

JavaScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerElement({
  map: map,
  position: position,
  title: "Uluru",
});

השלמת הקוד לדוגמה

אפשר לראות את הקוד המלא לדוגמה כאן:

TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerElement({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

HTML

<html>
  <head>
    <title>Add Map</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script>
  </body>
</html>

כדאי לנסות דוגמה

מידע נוסף על סמנים:

טיפים ופתרון בעיות

  • אפשר לשנות אפשרויות כמו סגנון ומאפיינים כדי להתאים אישית את המפה. עבור מידע נוסף על התאמה אישית של מפות, ניתן לקרוא את המדריכים עיצוב, וכן שרטוט על המפה.
  • צריך להשתמש ב-Developer Tools Console בדפדפן האינטרנט כדי לבדוק ולהפעיל את לקרוא דוחות שגיאות ולפתור בעיות בקוד.
  • אפשר להשתמש במקשי הקיצור הבאים כדי לפתוח את המסוף ב-Chrome:
    Command+Option+J (ב-Mac) או Control+Shift+J (ב-Windows).
  • פועלים לפי השלבים הבאים כדי לקבל את קו הרוחב קו האורך של מיקום במפות Google.

    1. פותחים את מפות Google בדפדפן.
    2. יש ללחוץ לחיצה ימנית על המיקום המדויק במפה שעבורו דרושה של הקואורדינטות.
    3. בוחרים באפשרות מה יש כאן בתפריט ההקשר שמופיע. המפה מציגה כרטיס בתחתית המסך. חיפוש קו הרוחב וקו האורך בשורה האחרונה של הכרטיס.
  • ניתן להמיר כתובת לקואורדינטות של קו אורך וקו רוחב באמצעות שירות קידוד גיאוגרפי. המדריכים למפתחים מספקים מידע מפורט על התחלת השימוש בשירות המרת כתובות לקואורדינטות (geocoding).