הוספת מפה של Google עם סמן לאתר

מבוא

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

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


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>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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>

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

איך מתחילים

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

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

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

שלב 1: יצירת דף HTML

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

<!doctype html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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>

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

<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% כדי להציג את הרוחב של דף האינטרנט.

טוען ה-Botstrap מכין את ה-API של JavaScript למפות Google לטעינה (לא תתבצע טעינה של ספריות עד להפעלת 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>

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

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

בקטע הזה נסביר איך לטעון את 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 הוא הזום הנמוך ביותר, ומציג את כדור הארץ כולו. הגדר את ערך הזום גבוה יותר כדי להתקרב ל-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",
});

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

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

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

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

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

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

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

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

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

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

  7. מעתיקים את כל הקוד של המדריך מהדף הזה לכלי לעריכת טקסט.

  8. מחליפים את הערך של הפרמטר key בכתובת ה-URL במפתח API משלכם (זהו מפתח ה-API שקיבלתם).

    <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>
    
  9. שומרים את הקובץ בשם שמסתיים ב-.html, למשל index.html.

  10. כדי לטעון את קובץ ה-HTML בדפדפן אינטרנט, גוררים אותו משולחן העבודה לדפדפן. לחלופין, לחיצה כפולה על הקובץ פועלת ברוב מערכות ההפעלה.

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

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

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