LoginSignup
6
14

More than 5 years have passed since last update.

Leaflet のポップアップのカスタマイズ

Posted at

Leaflet のポップアップは A pretty CSS3 popup. Easily customizable. とのことなので、実際に CSS でカスタマイズしてみます。

1. シナリオ

デフォルトのこれを

image

こんなふうにしてみました

image

2. ソース

http://leafletjs.com/ のサンプルに対して CSS を数行追加すると完成です。

index.html
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Leaflet Popup CSS Hack</title>

  <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
  <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
  <style>
    body {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }

    #map {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
    }

    .leaflet-popup-content-wrapper,
    .leaflet-popup-tip {
      background: black;
      border-color: orange;
    }

    .leaflet-popup-content,
    a.leaflet-popup-close-button {
      color: orange !important;
      font: bold 14pt monospace;
    }

    .leaflet-popup-content-wrapper {
      border-width: 3px;
      border-style: solid;
    }

    .leaflet-popup-tip-container {
      margin-top: -3px;
      height: 23px;
    }

    .leaflet-popup-tip {
      border-style: solid;
      border-width: 0 3px 3px 0;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    L.marker([51.5, -0.09]).addTo(map)
      .bindPopup('A pretty CSS3 popup.<br/> Easily customizable.')
      .openPopup();
  </script>
</body>

</html>

3. 解説

ポップアップ配下の DOM ツリーはだいたい以下のような構造になっているので、これをもとに CSS を追加定義していくだけです。

+ div.leaflet-popup
    + a.leaflet-popup-close-button
        + "x"
    + div.leaflet-popup-content-wrapper
        + div.leaflet-popup-content
            + "A pretty CSS3 popup..."
    + div.leaflet-popup-tip-container
        + div.leaflet-popup-tip
element note
div.leaflet-popup ルートコンテナ
a.leaflet-popup-close-button 右上にある閉じるボタン
div.leaflet-popup-content-wrapper ポップアップの本体
div.leaflet-popup-content ポップアップの文字列のプレースホルダ
div.leaflet-popup-tip-container ポップアップ下の三角形を保持するための領域
div.leaflet-popup-tip ポップアップ下の三角形本体
  • ポップアップの背景色と枠線は div.leaflet-popup-content-wrapper と div.leaflet-popup-tip に対して指定
  • 枠線をつけて膨らんだ分、div.leaflet-popup-tip-container のマージンを変更して調節
  • フォントと文字色の変更は a.leaflet-popup-close-button と div.leaflet-popup-content に対して設定
  • a.leaflet-popup-close-button はデフォルトでは灰色が指定されているので、!important をつけて上書き

4. メモ

Leaflet 0.7 系でも 1.0 系でもここの DOM 構造は共通しているので、問題なく動くはず。

6
14
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
6
14