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

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

ב-HTML, צריך להגדיר את המאפיין gmp-clickable ברכיב gmp-advanced-marker כדי שהסמן יהיה קליקבילי. השתמשו ב-advancedMarker.addEventListener כדי לטפל באירועי קליקים.

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-clickable
      ></gmp-advanced-marker>
      <gmp-advanced-marker
        position="47.648994,-122.3503845"
        title="Seattle, WA"
        gmp-clickable
      ></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. הקוד מבסס את המאזינים לכל סמן, ומציג חלון מידע בכל פעם שלוחצים על כל סמן.

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