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

מבוא

המדריך הזה מראה איך להוסיף לדף אינטרנט מפה פשוטה של 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. קבלת מפתח 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>
    <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>

אפשר להוסיף כותרת ברמה 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 לערך גדול מ-0px. במקרה כזה, div מוגדר לגובה של 400 פיקסלים, ולרוחב של 100% להצגה לכל רוחב דף האינטרנט.

ה-Bottrap load מכין את ה-JavaScript API של מפות 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>

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

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

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

הקוד שבהמשך מציב סמן במפה. המאפיין 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",
});

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

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

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

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