LoginSignup
1
3

More than 3 years have passed since last update.

地図の四隅にボタンを追加する

Last updated at Posted at 2020-11-30

Mapbox の地図の左上には、拡大・縮小ボタンなどが表示されています。
ここに任意のボタンを追加してみます。

image.png

// Control implemented as ES6 class
class HelloWorldControl {
  onAdd(map) {
    this.map = map;

    const homeButton = document.createElement('button');
    homeButton.innerHTML = '<i class="fa fa-home" aria-hidden="true"></i>';
    homeButton.addEventListener('click', (e) => {
        alert('Home button click');
    });

    this.container = document.createElement('div');
    this.container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group';
    this.container.appendChild(homeButton);

    return this.container;
  }

  onRemove() {
    this.container.parentNode.removeChild(this.container);
    this.map = undefined;
  }
}

const opt = {
  container: 'map',
  style: {
    version: 8,
    sources: {
      OSM: {
        type: "raster",
        tiles: [
          "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png",
        ],
        tileSize: 256,
        attribution:
        "OpenStreetMap",
      },
    },
    layers: [{
      id: "BASEMAP",
      type: "raster",
      source: "OSM",
      minzoom: 0,
      maxzoom: 18,
    }],
  },      
};

opt.center = [138.73072, 35.36286];
opt.zoom = 13;
const map = new mapboxgl.Map(opt);

map.addControl(new mapboxgl.NavigationControl({
  showCompass: false,
}));

map.addControl(new HelloWorldControl(), 'top-right');

HelloworldControl というボタンを示すクラスを実装し、そのインスタンスを map.addControl() します。
HelloworldControl の実装での注意点は、コンテナとなる div 要素に mapboxgl-ctrl mapboxgl-ctrl-group のクラスを設定してあげることです。
これを行うと、ボタンの見た目が、拡大・縮小などと同じになります。
逆に見た目を完全に独自にしたい場合はこれを行わず、自分でデザインすることになります。

ボタンの表示位置は画面の四隅(top-right, bottom-right, bottom-left, top-left)が選べます。
位置の細かい指定はできず、地図隅からのマージンも指定できません。
恐らくですが、HelloworldControl の実装方法次第では、隅からの余白を空けることはできるのだとおもいます。

「ボタンが押された」ことの検知も HelloworldControl の実装で行います。Mapbox がサポートできる事はないです。

参考

1
3
2

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
1
3