カスタムのオーバーレイ

プラットフォームを選択: Android iOS JavaScript

はじめに

オーバーレイは緯度と経度で表される座標に紐付いた地図上のオブジェクトで、地図をドラッグしたりズームしたりすると連動して動きます。事前に定義されているオーバーレイ タイプについては、地図上への図形描画をご覧ください。

Maps JavaScript API の OverlayView クラスを使うと、独自のカスタム オーバーレイを作成できます。OverlayView は基本クラスで、このクラスにはオーバーレイの作成時に実装する必要のある複数のメソッドが含まれています。また、画面上の座標と地図上の位置を変換するメソッドもあります。

カスタム オーバーレイを追加する

カスタム オーバーレイを作成する手順の概要は次のとおりです。

  • カスタム オーバーレイ オブジェクトの prototypegoogle.maps.OverlayView() の新しいインスタンスに設定します。実際には、これはオーバーレイ クラスのサブクラスになります。
  • カスタム オーバーレイ用のコンストラクタを作成し、すべての初期化パラメータを設定します。
  • プロトタイプ内に onAdd() メソッドを実装し、オーバーレイを地図に貼り付けます。地図にオーバーレイを貼り付けられる状態になると、OverlayView.onAdd() が呼び出されます。
  • プロトタイプ内に draw() メソッドを実装し、オブジェクトの表示処理を行います。オブジェクトが初めて表示されるときに、OverlayView.draw() が呼び出されます。
  • onRemove() メソッドを実装して、オーバーレイに追加したすべての要素を削除する必要もあります。

以下で各ステップの詳細を説明します。機能する完全なサンプルコードについては、こちらのサンプルコードをご覧ください。

オーバーレイをサブクラス化する

以下の例では、OverlayView を使って単純なイメージ オーバーレイを作成しています。

ここで USGSOverlay クラス用のコンストラクタを作成し、渡されたパラメータを新しいオブジェクトのプロパティとして初期化します。

TypeScript

/**  * The custom USGSOverlay object contains the USGS image,  * the bounds of the image, and a reference to the map.  */ class USGSOverlay extends google.maps.OverlayView {   private bounds: google.maps.LatLngBounds;   private image: string;   private div?: HTMLElement;    constructor(bounds: google.maps.LatLngBounds, image: string) {     super();      this.bounds = bounds;     this.image = image;   }

JavaScript

/**  * The custom USGSOverlay object contains the USGS image,  * the bounds of the image, and a reference to the map.  */ class USGSOverlay extends google.maps.OverlayView {   bounds;   image;   div;   constructor(bounds, image) {     super();     this.bounds = bounds;     this.image = image;   }

オーバーレイのコンストラクタでは、このオーバーレイをまだ地図に貼り付けることはできません。まずは、地図へのオブジェクトの表示順序を指定する地図ペインが、すべて利用可能であることを確認する必要があります。API には、これを確認できるヘルパー メソッドがあります。次のセクションでは、そのメソッドの扱いについて説明します。

オーバーレイを初期化する

オーバーレイが最初にインスタンス化され、表示できる状態になったら、ブラウザの DOM を介して地図に貼り付ける必要があります。API はオーバーレイの onAdd() メソッドを呼び出すことで、オーバーレイが地図に追加されたことを示します。このメソッドを処理するために、イメージを保持する <div> を作成して <img> 要素を追加します。これを <div> に貼り付けて、オーバーレイを地図のペインの 1 つに貼り付けます。なお、ペインとは DOM ツリーのノードです。

MapPanes タイプのペインは、地図上にレイヤを重ねる順番を指定します。以下のペインが利用可能で、先に示されているペインほど下側に積み重ねられます。

  • mapPane は最下層のペインでタイルの上にあります。DOM イベントを受け取らない場合があります。(ペイン 0)
  • overlayLayer にはポリラインやポリゴン、地面オーバーレイとタイルレイヤ オーバーレイが含まれます。DOM イベントを受け取らない場合があります。(ペイン 1)
  • markerLayer にはマーカーが含まれています。DOM イベントを受け取らない場合があります。(ペイン 2)
  • overlayMouseTarget には DOM イベントを受け取る要素が含まれます。(ペイン 3)
  • floatPane には、情報ウィンドウが含まれます。このペインは地図オーバーレイの中で最も上にあります。(ペイン 4)

ここでは「地面オーバーレイ」の画像を表示するため、overlayLayer ペインを使います。このペインを取得したら、オブジェクトを子として付けます。

TypeScript

/**  * onAdd is called when the map's panes are ready and the overlay has been  * added to the map.  */ onAdd() {   this.div = document.createElement("div");   this.div.style.borderStyle = "none";   this.div.style.borderWidth = "0px";   this.div.style.position = "absolute";    // Create the img element and attach it to the div.   const img = document.createElement("img");    img.src = this.image;   img.style.width = "100%";   img.style.height = "100%";   img.style.position = "absolute";   this.div.appendChild(img);    // Add the element to the "overlayLayer" pane.   const panes = this.getPanes()!;    panes.overlayLayer.appendChild(this.div); }

JavaScript

/**  * onAdd is called when the map's panes are ready and the overlay has been  * added to the map.  */ onAdd() {   this.div = document.createElement("div");   this.div.style.borderStyle = "none";   this.div.style.borderWidth = "0px";   this.div.style.position = "absolute";    // Create the img element and attach it to the div.   const img = document.createElement("img");    img.src = this.image;   img.style.width = "100%";   img.style.height = "100%";   img.style.position = "absolute";   this.div.appendChild(img);    // Add the element to the "overlayLayer" pane.   const panes = this.getPanes();    panes.overlayLayer.appendChild(this.div); }

オーバーレイを描画する

上記のコードではまだ、画面表示を始めていません。最初にオーバーレイを追加したときなど、地図上にオーバーレイを描画する必要がある際、API では個別の draw() メソッドを呼び出します。

そのため、この draw() メソッドを実装し、getProjection() を使用してオーバーレイの MapCanvasProjection を取得し、オブジェクトの右上隅と左下隅を固定する正確な座標を計算します。これで、<div> のサイズを変更できるようになります。あとはオーバーレイのコンストラクタで指定した境界に合うように、画像のサイズが変更されます。

TypeScript

draw() {   // We use the south-west and north-east   // coordinates of the overlay to peg it to the correct position and size.   // To do this, we need to retrieve the projection from the overlay.   const overlayProjection = this.getProjection();    // Retrieve the south-west and north-east coordinates of this overlay   // in LatLngs and convert them to pixel coordinates.   // We'll use these coordinates to resize the div.   const sw = overlayProjection.fromLatLngToDivPixel(     this.bounds.getSouthWest()   )!;   const ne = overlayProjection.fromLatLngToDivPixel(     this.bounds.getNorthEast()   )!;    // Resize the image's div to fit the indicated dimensions.   if (this.div) {     this.div.style.left = sw.x + "px";     this.div.style.top = ne.y + "px";     this.div.style.width = ne.x - sw.x + "px";     this.div.style.height = sw.y - ne.y + "px";   } }

JavaScript

draw() {   // We use the south-west and north-east   // coordinates of the overlay to peg it to the correct position and size.   // To do this, we need to retrieve the projection from the overlay.   const overlayProjection = this.getProjection();   // Retrieve the south-west and north-east coordinates of this overlay   // in LatLngs and convert them to pixel coordinates.   // We'll use these coordinates to resize the div.   const sw = overlayProjection.fromLatLngToDivPixel(     this.bounds.getSouthWest(),   );   const ne = overlayProjection.fromLatLngToDivPixel(     this.bounds.getNorthEast(),   );    // Resize the image's div to fit the indicated dimensions.   if (this.div) {     this.div.style.left = sw.x + "px";     this.div.style.top = ne.y + "px";     this.div.style.width = ne.x - sw.x + "px";     this.div.style.height = sw.y - ne.y + "px";   } }

カスタム オーバーレイを削除する

ここで、地図からオーバーレイを完全に削除する onRemove() メソッドも追加します。

TypeScript

/**  * The onRemove() method will be called automatically from the API if  * we ever set the overlay's map property to 'null'.  */ onRemove() {   if (this.div) {     (this.div.parentNode as HTMLElement).removeChild(this.div);     delete this.div;   } }

JavaScript

/**  * The onRemove() method will be called automatically from the API if  * we ever set the overlay's map property to 'null'.  */ onRemove() {   if (this.div) {     this.div.parentNode.removeChild(this.div);     delete this.div;   } }

カスタム オーバーレイの表示 / 非表示を切り替える

単純にオーバーレイを作成 / 削除するのではなく、表示 / 非表示を切り替えたい場合は、独自の hide() メソッドと show() メソッドを実装してオーバーレイの表示状態を変更できます。代わりに、地図の DOM からオーバーレイを外すこともできますが、この操作のコストは若干高くなります。なお、地図の DOM に再度オーバーレイを貼り付けると、オーバーレイの onAdd() メソッドがもう一度呼び出されます。

以下のサンプルでは、コンテナ <div> の表示状態を切り替える hide()show() メソッドをオーバーレイのプロトタイプに追加しています。さらにオーバーレイを地図に貼り付けたり、地図から外したりする toggleDOM() メソッドも追加しています。

TypeScript

/**  *  Set the visibility to 'hidden' or 'visible'.  */ hide() {   if (this.div) {     this.div.style.visibility = "hidden";   } }  show() {   if (this.div) {     this.div.style.visibility = "visible";   } }  toggle() {   if (this.div) {     if (this.div.style.visibility === "hidden") {       this.show();     } else {       this.hide();     }   } }  toggleDOM(map: google.maps.Map) {   if (this.getMap()) {     this.setMap(null);   } else {     this.setMap(map);   } }

JavaScript

/**  *  Set the visibility to 'hidden' or 'visible'.  */ hide() {   if (this.div) {     this.div.style.visibility = "hidden";   } } show() {   if (this.div) {     this.div.style.visibility = "visible";   } } toggle() {   if (this.div) {     if (this.div.style.visibility === "hidden") {       this.show();     } else {       this.hide();     }   } } toggleDOM(map) {   if (this.getMap()) {     this.setMap(null);   } else {     this.setMap(map);   } }

ボタン コントロールを追加する

toggle メソッドと toggleDom メソッドをトリガーするために、ボタン コントロールが地図に追加されます。

TypeScript

const toggleButton = document.createElement("button");  toggleButton.textContent = "Toggle"; toggleButton.classList.add("custom-map-control-button");  const toggleDOMButton = document.createElement("button");  toggleDOMButton.textContent = "Toggle DOM Attachment"; toggleDOMButton.classList.add("custom-map-control-button");  toggleButton.addEventListener("click", () => {   overlay.toggle(); });  toggleDOMButton.addEventListener("click", () => {   overlay.toggleDOM(map); });  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton);

JavaScript

const toggleButton = document.createElement("button");  toggleButton.textContent = "Toggle"; toggleButton.classList.add("custom-map-control-button");  const toggleDOMButton = document.createElement("button");  toggleDOMButton.textContent = "Toggle DOM Attachment"; toggleDOMButton.classList.add("custom-map-control-button"); toggleButton.addEventListener("click", () => {   overlay.toggle(); }); toggleDOMButton.addEventListener("click", () => {   overlay.toggleDOM(map); }); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton); map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton);

完全なサンプルコード

完全なサンプルコードを以下に示します。

TypeScript

// This example adds hide() and show() methods to a custom overlay's prototype. // These methods toggle the visibility of the container <div>. // overlay to or from the map.  function initMap(): void {   const map = new google.maps.Map(     document.getElementById("map") as HTMLElement,     {       zoom: 11,       center: { lat: 62.323907, lng: -150.109291 },       mapTypeId: "satellite",     }   );    const bounds = new google.maps.LatLngBounds(     new google.maps.LatLng(62.281819, -150.287132),     new google.maps.LatLng(62.400471, -150.005608)   );    // The photograph is courtesy of the U.S. Geological Survey.   let image = "https://developers.google.com/maps/documentation/javascript/";    image += "examples/full/images/talkeetna.png";    /**    * The custom USGSOverlay object contains the USGS image,    * the bounds of the image, and a reference to the map.    */   class USGSOverlay extends google.maps.OverlayView {     private bounds: google.maps.LatLngBounds;     private image: string;     private div?: HTMLElement;      constructor(bounds: google.maps.LatLngBounds, image: string) {       super();        this.bounds = bounds;       this.image = image;     }      /**      * onAdd is called when the map's panes are ready and the overlay has been      * added to the map.      */     onAdd() {       this.div = document.createElement("div");       this.div.style.borderStyle = "none";       this.div.style.borderWidth = "0px";       this.div.style.position = "absolute";        // Create the img element and attach it to the div.       const img = document.createElement("img");        img.src = this.image;       img.style.width = "100%";       img.style.height = "100%";       img.style.position = "absolute";       this.div.appendChild(img);        // Add the element to the "overlayLayer" pane.       const panes = this.getPanes()!;        panes.overlayLayer.appendChild(this.div);     }      draw() {       // We use the south-west and north-east       // coordinates of the overlay to peg it to the correct position and size.       // To do this, we need to retrieve the projection from the overlay.       const overlayProjection = this.getProjection();        // Retrieve the south-west and north-east coordinates of this overlay       // in LatLngs and convert them to pixel coordinates.       // We'll use these coordinates to resize the div.       const sw = overlayProjection.fromLatLngToDivPixel(         this.bounds.getSouthWest()       )!;       const ne = overlayProjection.fromLatLngToDivPixel(         this.bounds.getNorthEast()       )!;        // Resize the image's div to fit the indicated dimensions.       if (this.div) {         this.div.style.left = sw.x + "px";         this.div.style.top = ne.y + "px";         this.div.style.width = ne.x - sw.x + "px";         this.div.style.height = sw.y - ne.y + "px";       }     }      /**      * The onRemove() method will be called automatically from the API if      * we ever set the overlay's map property to 'null'.      */     onRemove() {       if (this.div) {         (this.div.parentNode as HTMLElement).removeChild(this.div);         delete this.div;       }     }      /**      *  Set the visibility to 'hidden' or 'visible'.      */     hide() {       if (this.div) {         this.div.style.visibility = "hidden";       }     }      show() {       if (this.div) {         this.div.style.visibility = "visible";       }     }      toggle() {       if (this.div) {         if (this.div.style.visibility === "hidden") {           this.show();         } else {           this.hide();         }       }     }      toggleDOM(map: google.maps.Map) {       if (this.getMap()) {         this.setMap(null);       } else {         this.setMap(map);       }     }   }    const overlay: USGSOverlay = new USGSOverlay(bounds, image);    overlay.setMap(map);    const toggleButton = document.createElement("button");    toggleButton.textContent = "Toggle";   toggleButton.classList.add("custom-map-control-button");    const toggleDOMButton = document.createElement("button");    toggleDOMButton.textContent = "Toggle DOM Attachment";   toggleDOMButton.classList.add("custom-map-control-button");    toggleButton.addEventListener("click", () => {     overlay.toggle();   });    toggleDOMButton.addEventListener("click", () => {     overlay.toggleDOM(map);   });    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton);   map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton); }  declare global {   interface Window {     initMap: () => void;   } } window.initMap = initMap;

JavaScript

// This example adds hide() and show() methods to a custom overlay's prototype. // These methods toggle the visibility of the container <div>. // overlay to or from the map. function initMap() {   const map = new google.maps.Map(document.getElementById("map"), {     zoom: 11,     center: { lat: 62.323907, lng: -150.109291 },     mapTypeId: "satellite",   });   const bounds = new google.maps.LatLngBounds(     new google.maps.LatLng(62.281819, -150.287132),     new google.maps.LatLng(62.400471, -150.005608),   );   // The photograph is courtesy of the U.S. Geological Survey.   let image = "https://developers.google.com/maps/documentation/javascript/";    image += "examples/full/images/talkeetna.png";   /**    * The custom USGSOverlay object contains the USGS image,    * the bounds of the image, and a reference to the map.    */   class USGSOverlay extends google.maps.OverlayView {     bounds;     image;     div;     constructor(bounds, image) {       super();       this.bounds = bounds;       this.image = image;     }     /**      * onAdd is called when the map's panes are ready and the overlay has been      * added to the map.      */     onAdd() {       this.div = document.createElement("div");       this.div.style.borderStyle = "none";       this.div.style.borderWidth = "0px";       this.div.style.position = "absolute";        // Create the img element and attach it to the div.       const img = document.createElement("img");        img.src = this.image;       img.style.width = "100%";       img.style.height = "100%";       img.style.position = "absolute";       this.div.appendChild(img);        // Add the element to the "overlayLayer" pane.       const panes = this.getPanes();        panes.overlayLayer.appendChild(this.div);     }     draw() {       // We use the south-west and north-east       // coordinates of the overlay to peg it to the correct position and size.       // To do this, we need to retrieve the projection from the overlay.       const overlayProjection = this.getProjection();       // Retrieve the south-west and north-east coordinates of this overlay       // in LatLngs and convert them to pixel coordinates.       // We'll use these coordinates to resize the div.       const sw = overlayProjection.fromLatLngToDivPixel(         this.bounds.getSouthWest(),       );       const ne = overlayProjection.fromLatLngToDivPixel(         this.bounds.getNorthEast(),       );        // Resize the image's div to fit the indicated dimensions.       if (this.div) {         this.div.style.left = sw.x + "px";         this.div.style.top = ne.y + "px";         this.div.style.width = ne.x - sw.x + "px";         this.div.style.height = sw.y - ne.y + "px";       }     }     /**      * The onRemove() method will be called automatically from the API if      * we ever set the overlay's map property to 'null'.      */     onRemove() {       if (this.div) {         this.div.parentNode.removeChild(this.div);         delete this.div;       }     }     /**      *  Set the visibility to 'hidden' or 'visible'.      */     hide() {       if (this.div) {         this.div.style.visibility = "hidden";       }     }     show() {       if (this.div) {         this.div.style.visibility = "visible";       }     }     toggle() {       if (this.div) {         if (this.div.style.visibility === "hidden") {           this.show();         } else {           this.hide();         }       }     }     toggleDOM(map) {       if (this.getMap()) {         this.setMap(null);       } else {         this.setMap(map);       }     }   }    const overlay = new USGSOverlay(bounds, image);    overlay.setMap(map);    const toggleButton = document.createElement("button");    toggleButton.textContent = "Toggle";   toggleButton.classList.add("custom-map-control-button");    const toggleDOMButton = document.createElement("button");    toggleDOMButton.textContent = "Toggle DOM Attachment";   toggleDOMButton.classList.add("custom-map-control-button");   toggleButton.addEventListener("click", () => {     overlay.toggle();   });   toggleDOMButton.addEventListener("click", () => {     overlay.toggleDOM(map);   });   map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleDOMButton);   map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleButton); }  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; }  .custom-map-control-button {   background-color: #fff;   border: 0;   border-radius: 2px;   box-shadow: 0 1px 4px -1px rgba(0, 0, 0, 0.3);   margin: 10px;   padding: 0 0.5em;   font: 400 18px Roboto, Arial, sans-serif;   overflow: hidden;   height: 40px;   cursor: pointer; } .custom-map-control-button:hover {   background: rgb(235, 235, 235); } 

HTML

<html>   <head>     <title>Showing/Hiding Overlays</title>      <link rel="stylesheet" type="text/css" href="./style.css" />     <script type="module" src="./index.js"></script>   </head>   <body>     <div id="map"></div>      <!--        The `defer` attribute causes the script 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=weekly"       defer     ></script>   </body> </html>

サンプルを試す