הוספת מפה של Google לדף אינטרנט

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

סקירה כללית

כדי לטעון מפה, דף האינטרנט חייב לבצע את הפעולות הבאות:

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

הוספת מפה באמצעות רכיב gmp-map

הרכיב gmp-map הוא רכיב HTML מותאם אישית שנוצר באמצעות רכיבי אינטרנט. כדי להוסיף מפה לדף אינטרנט באמצעות רכיב gmp-map, יש לבצע את השלבים הבאים.

  1. בדף ה-HTML, מוסיפים את האלמנט script שמכיל את ה-Botstrap שמוגדר באמצעות מפתח ה-API, וכל אפשרות אחרת. ב-Botstrap בדוגמה הבאה, הפרמטר callback הושמט כי אין צורך בו.

    <script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=map,marker">
    
  2. בדף ה-HTML, מוסיפים רכיב gmp-map. צריך לציין את הקואורדינטות של קווי האורך והרוחב עבור center, וערך מרחק התצוגה עבור zoom. בדוגמה הזו מצוין גם מאפיין הסגנון height.

    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

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

<html>
  <head>
    <title>Add a Map using HTML</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>
    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

    <!-- 
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=beta"
      defer
    ></script>
  </body>
</html>

הוספת מפה באמצעות אלמנט div ו-JavaScript

הרכיב div עדיין נתמך לטעינת מפות. על מנת להוסיף מפה לדף אינטרנט באמצעות רכיב div, יש לבצע את השלבים הבאים.

  1. בדף ה-HTML, מוסיפים את הרכיב script שמכיל את טוען ה-Botstrap שמוגדר באמצעות מפתח ה-API, וכל אפשרות אחרת. לחלופין, מוסיפים את הקוד של טוען ה-Botstrap ישירות לקובץ TypeScript או JavaScript, בלי התגים script.

    <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>
    
  2. בדף ה-HTML, מוסיפים רכיב div שיכיל את המפה.

    <div id="map"></div>
    
  3. ב-CSS, מגדירים את גובה המפה ל-100%.

    #map {
      height: 100%;
    }
    
  4. בקובץ ה-JavaScript, יוצרים פונקציה לטעינת הספרייה maps ולאתחול המפה. צריך לציין את הקואורדינטות של קווי האורך והרוחב עבור center, ואת רמת הזום לשימוש עבור zoom.

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

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

TypeScript

let map: google.maps.Map;
async function initMap(): Promise<void> {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

JavaScript

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

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

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