勉強したことのメモ

Webエンジニア / プログラマが勉強したことのメモ。

Leafletにて表示されているマップを画像としてダウンロードさせる「leaflet-easyPrint」の利用方法

  JavaScript

Leafletにて何らかのボタンをクリックすると表示されているマップを画像としてダウンロードさせたい。調べたところ「leaflet-easyPrint」というプラグインで簡単に実装できた。以下にサンプルと実装方法をメモ。

 

leaflet-easyPrint

GitHub

https://github.com/rowanwins/leaflet-easyPrint

デモページ

http://rowanwins.github.io/leaflet-easyPrint/

CDN

CDNで使う場合は以下を記述する。

<script src="https://cdn.jsdelivr.net/npm/leaflet-easyprint@2.1.9/dist/bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/leaflet-easyprint@2.1.9/libs/leaflet.min.css" rel="stylesheet">

 

サンプル

https://taitan916.info/sample/leaflet.js/plugin/leaflet-easyPrint/

マップ左上の保存ボタン→サイズを選択すると画像がダウンロードされる筈。

 

実装方法

ソースコード

<div id="map" class="sidebar-map"></div>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.js"></script>

<script src="https://cdn.jsdelivr.net/npm/leaflet-easyprint@2.1.9/dist/bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/leaflet-easyprint@2.1.9/libs/leaflet.min.css" rel="stylesheet">

<script>
let map;
map = L.map('map');

//中心の経度緯度
const center = ['35.681236', '139.767125'];

//ズームレベル
const zoom = 12;

//マップの中心地とズームレベルを指定
map.setView(center, zoom);

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

//プラグインのオプション設定
const option = {
    sizeModes: ['Current', 'A4Landscape', 'A4Portrait'],
    filename: 'テストマップ',
    exportOnly: true,
    hideControlContainer: true
};

//プラグイン実行
const printer = L.easyPrint(option).addTo(map);
</script>

オプション設定について

オプション項目についてはこちらのページを参照すること。

 - JavaScript

  関連記事

Leafletで「leaflet-control-geocoder」プラグインを導入して住所検索機能を追加する方法

LeafletとOpenStreetMapでマップを表示させ、テキストボックスに ...

Leafletにて操作内容を履歴に残し「進む」「戻る」ボタンで履歴を実行できる「Leaflet.NavBar」の利用方法

Leafletにてマップ移動やズーム等、ユーザーの操作内容を履歴に残して、「進む ...

Leafletでマーカーを動的に変更し、変更状況をCookieに保存する方法

Leafletでポップアップ(フキダシ)内のボタンをクリックするとマーカーを動的 ...

Leafletのマップ状況をブラウザに保存し、再表示時に復元する「Leaflet.RestoreView」の利用方法

Leafletのマップ状況をブラウザ(cookie等)に保存し、ページリロード時 ...

Leafletで「leaflet.sprite」プラグインを導入してマーカーの色を変更する方法

LeafletとOpenStreetMapでマップ上にマーカーを複数設置したい。 ...