Maps JavaScript API'deki Web Bileşenleri (Önizleme)

Web Bileşenleri; özel ve yeniden kullanılabilir HTML öğelerinde HTML, CSS ve JS'yi kapsayan popüler bir W3C standardıdır. Yeniden kullanılabilir bu bileşenler, atomik işlevlerden (bir yerin yıldız puanını görüntülemek gibi) daha karmaşık iş mantığına kadar çeşitlilik gösterebilir. Bu kılavuzda, Maps JavaScript API'de kullanılabilen Web Bileşenleri açıklanmaktadır.

Standardın kendisi hakkında daha fazla bilgi için Web Bileşenleri konusuna bakın.

Kitle

Bu belge, Web Bileşenleri ile uygulamaları keşfetmeye ve geliştirmeye hızlıca başlayabilmeniz için tasarlanmıştır. HTML ve CSS programlama kavramlarına aşina olmalısınız.

Harita Görüntüleyin

Web Bileşenleri hakkında bilgi edinmeye başlamanın en kolay yolu bir örnek görmektir. Aşağıdaki örnekte, San Jose bölgesinin bir haritası gösterilmektedir.

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>

Örneği Deneyin

Bu örnekte dikkat edilmesi gereken birkaç nokta vardır:

  1. Haritalar JavaScript API'si eşzamansız olarak adlandırılır. Geri çağırma işlevi, API'nin ne zaman yüklendiğini öğrenmek için kullanılır.
  2. Haritanın sunumu, <gmp-map> özel öğesi ile tanımlanır.
  3. Harita özellikleri, <gmp-map> özel öğesinde özellikler belirtilerek tanımlanır.
  4. Stil, özel öğelere satır içi olarak uygulanabilir veya ayrı bir CSS dosyasında bildirilebilir.

Temel haritanın stilini belirleme

Harita kimliği, belirli bir harita stili veya özelliğiyle ilişkilendirilen bir tanımlayıcıdır. İsteğe bağlı bulut yapılandırma özelliklerinden yararlanmak için DEMO_MAP_ID stilini oluşturan bulut tabanlı haritaları kendi harita kimliğinizle değiştirin. Harita kimliği oluşturmayı ve özel stil yapılandırmayı öğrenmek için Bulut Tabanlı Harita Stili'ni ziyaret edin.

Haritaya işaretçi ekleme

Karmaşık içerik hiyerarşileri oluşturmak için yerleşik HTML etiketlerinin iç içe yerleştirilmesi gibi, bir veya daha fazla harita işaretçisini görüntülemek için <gmp-advanced-marker> öğeleri de öğenin içine yerleştirilebilir.

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>

Örneği Deneyin

Burada, <gmp-map> özel öğesinin içine iki <gmp-advanced-marker> öğesi ekledik. title metni, belirtilen öğe için ek bir fareyle üzerine gelinen metin ve erişilebilirlik etiketi sağlar.

JavaScript Etkinlikleri

Web Bileşenlerinin önemli bir avantajı, kullanım kolaylığıdır. Kullanıcı, birkaç satır kod kullanarak sınırlı JavaScript veya gelişmiş programlama bilgisine sahip bir Harita görüntüleyebilir. Uygulandıktan sonra, kod diğer HTML öğelerinin bilinen kalıplarını izler. Örneğin, harita veya işaretçi tıklaması gibi Gelişmiş İşaretçi işlemlerine tepki vermek için yerel tarayıcı etkinlik sistemi kullanılabilir.

HTML'nizde, bir işaretçiyi tıklanabilir yapmak için gmp-advanced-marker öğesinde gmp-clickable özelliğini ayarlayın. Tıklama etkinliklerini işlemek için advancedMarker.addEventListener öğesini kullanın.

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>

Örneği Deneyin

Bu örnekte initMap, Maps JavaScript API tamamen yüklendikten sonra gerekli geri çağırma işlevini temsil etmektedir. Kod, her bir işaretçi için işleyiciler oluşturur ve her bir işaretçi tıklandığında bir bilgi penceresi sunar.

Sırada ne var?