רכיבי אינטרנט ב-JavaScript JavaScript API (תצוגה מקדימה)

Web Components (רכיבי Web) הם תקן W3C פופולרי, שמקיף HTML, CSS ו-JS ברכיבי HTML מותאמים אישית או לשימוש חוזר. הרכיבים שניתנים לשימוש חוזר יכולים לנוע מפונקציות פונקציונליות אטומיות כמו הצגת דירוג הכוכבים של מקום, ועד ללוגיקה עסקית מורכבת יותר. במדריך הזה מתוארים רכיבי האינטרנט שזמינים ב-Maps JavaScript API.

למידע נוסף על התקן עצמו, ניתן לעיין במאמר רכיבי אינטרנט.

קהל

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

הצגת מפה

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

TypeScript

// This example adds a map using web components.
function initMap(): void {
    console.log('Maps JavaScript API loaded.');
}

declare global {
    interface Window {
        initMap: () => void;
    }
}
window.initMap = initMap;

JavaScript

// This example adds a map using web components.
function initMap() {
  console.log("Maps JavaScript API loaded.");
}

window.initMap = 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;
}

gmp-map {
  height: 400px;
}

HTML

<html>
  <head>
    <title>Add a Map Web Component</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"
    ></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>

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

בדוגמה הזו יש כמה דברים שכדאי לשים לב אליהם:

  1. ה-API של JavaScript של מפות Google נקרא באופן אסינכרוני. פונקציית הקריאה החוזרת משמשת כדי לדעת מתי ה-API נטען.
  2. הצגת המפה מוגדרת באמצעות הרכיב המותאם אישית <gmp-map>.
  3. מאפייני המפה מוגדרים על ידי ציון המאפיינים ברכיב המותאם אישית <gmp-map>.
  4. אפשר להחיל את העיצוב בתוך השורה על רכיבים מותאמים אישית או להצהיר על העיצוב בקובץ CSS נפרד.

עיצוב המפה הבסיסית

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

הוספת סמנים למפה

בדיוק כמו שניתן להציב תגי HTML מובנים כדי ליצור היררכיות תוכן מורכבות, ניתן גם לקנן <gmp-advanced-marker> בתוך רכיב כדי להציג סמן מפה אחד או יותר.

TypeScript

// This example adds a map with markers, using web components.
function initMap(): void {
    console.log('Maps JavaScript API loaded.');
}

declare global {
    interface Window {
        initMap: () => void;
    }
}
window.initMap = initMap;

JavaScript

// This example adds a map with markers, using web components.
function initMap() {
  console.log("Maps JavaScript API loaded.");
}

window.initMap = 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;
}

gmp-map {
  height: 400px;
}

HTML

<html>
  <head>
    <title>Add a Map with Markers using Web Components</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="43.4142989,-124.2301242" zoom="4" map-id="DEMO_MAP_ID">
      <gmp-advanced-marker
        position="37.4220656,-122.0840897"
        title="Mountain View, CA"
      ></gmp-advanced-marker>
      <gmp-advanced-marker
        position="47.648994,-122.3503845"
        title="Seattle, WA"
      ></gmp-advanced-marker>
    </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&libraries=marker&v=beta"
      defer
    ></script>
  </body>
</html>

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

כאן הוספנו שני רכיבי <gmp-advanced-marker> לרכיב המותאם אישית <gmp-map>. הטקסט של title מספק טקסט מרחף נוסף ותווית נגישות עבור הרכיב שצוין.

אירועי JavaScript

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

TypeScript

// This example adds a map using web components.
function initMap(): void {
  console.log('Maps JavaScript API loaded.');
  const advancedMarkers = document.querySelectorAll("#marker-click-event-example gmp-advanced-marker");
  for (const advancedMarker of advancedMarkers) {

    customElements.whenDefined(advancedMarker.localName).then(async () => {
      advancedMarker.addEventListener('gmp-click', async () => {

        const infoWindow = new google.maps.InfoWindow({
          //@ts-ignore
          content: advancedMarker.title,
        });
        infoWindow.open({
          //@ts-ignore
          anchor: advancedMarker
        });
      });
    });
  }
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// This example adds a map using web components.
function initMap() {
  console.log("Maps JavaScript API loaded.");

  const advancedMarkers = document.querySelectorAll(
    "#marker-click-event-example gmp-advanced-marker",
  );

  for (const advancedMarker of advancedMarkers) {
    customElements.whenDefined(advancedMarker.localName).then(async () => {
      advancedMarker.addEventListener("gmp-click", async () => {
        const infoWindow = new google.maps.InfoWindow({
          //@ts-ignore
          content: advancedMarker.title,
        });

        infoWindow.open({
          //@ts-ignore
          anchor: advancedMarker,
        });
      });
    });
  }
}

window.initMap = 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;
}

gmp-map {
  height: 400px;
}

HTML

<html>
  <head>
    <title>Add a Map Web Component with Events</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
      id="marker-click-event-example"
      center="43.4142989,-124.2301242"
      zoom="4"
      map-id="DEMO_MAP_ID"
    >
      <gmp-advanced-marker
        position="37.4220656,-122.0840897"
        title="Mountain View, CA"
      ></gmp-advanced-marker>
      <gmp-advanced-marker
        position="47.648994,-122.3503845"
        title="Seattle, WA"
      ></gmp-advanced-marker>
    </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&libraries=marker&v=beta"
      defer
    ></script>
  </body>
</html>

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

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

המאמרים הבאים