3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ZENRIN Maps APIでマウスホイールでの拡大縮小が完了したイベントをキャッチ

Last updated at Posted at 2025-03-28

はじめに

前回 ZENRIN Maps APIで小学校区、中学校区を表示してみた
ZENRIN Maps APIに用意されているマップイベントには
マウスホイールで地図を拡大縮小した際に"操作完了"をキャッチするイベントがないことをあげました

ZENRIN Maps APIに用意されているハンドラ

なので今回は、そのマウスホイール操作による地図拡大縮小の完了をキャッチする処理を作成してみます

準備

ZENRIN Maps API を利用しています
無料トライアルページ
2ヶ月間無料で利用できます

方法

簡単な方法として、wheelイベントとsetTimeout()を使用します

基本構文

wheelイベント

addEventListener('wheel', (event) => {});

イベントハンドラ「wheel」は、
マウスホイールを操作している間イベントが発火します

setTimeout()メソッド

setTimeout(関数, 遅延時間);

遅延時間(ミリ秒)に達すると関数が実行されます

結論

let wheelTimeout; // タイムアウトID ≒ タイマー
mapElement.addEventListener("wheel", function (e) { // 操作中は何度も発火する
  // 操作中は都度タイムアウトIDを破棄
  if (wheelTimeout) {
    clearTimeout(wheelTimeout);  // 古いタイマーを破棄
  }

  // 操作中はイベント発火都度、新たなタイムアウトIDが作られる
  // つまり、操作中はwheelTimeoutが上書きされ続ける
  wheelTimeout = setTimeout(() => {
    // ホイール操作が止まってもタイマーは動いているので、
    // 操作が止まって500ms経過するここの処理が呼ばれる
    alert('wheel operation completed')
    clearTimeout(wheelTimeout); // タイマーを破棄
  }, 500);
});

コード全体

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>

    <script src="https://test-js.zmaps-api.com/zma_loader.js?key=[APIキー]&auth=referer"></script>

    <style>
      body {margin: 0; padding: 0;}
      #ZMap {position: absolute; top: 0; bottom: 0; width: 100%;}
    </style>

  </head>
  <body>
    <div id="ZMap"></div>

    <script>
      let map;
      ZMALoader.setOnLoad(function (mapOptions, error) {
        if (error) {
          console.error(error)
          return
        }

        const lat = 35.681406, lng = 139.767132;
        const mapElement = document.getElementById('ZMap');
        mapOptions.center = new ZDC.LatLng(lat, lng);

        map = new ZDC.Map(
          mapElement,
          mapOptions,
          function() {
            let wheelTimeout;
            mapElement.addEventListener("wheel", function (e) {
              if (wheelTimeout) {
                clearTimeout(wheelTimeout);
              }

              wheelTimeout = setTimeout(() => {
                alert('wheel operation completed')
                clearTimeout(wheelTimeout);
              }, 500);
            });
          },
          function() {
          }
        );
      })
    </script>
  </body>
</html>
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?