LoginSignup
12
7

More than 5 years have passed since last update.

地図ライブラリ「Leaflet」で地図上に筋斗雲の現在地をマーキングする

Posted at

本日も地図ライブラリ「Leaflet」に関する記事です。
以前は、Cluster機能をご紹介しました。(地図ライブラリ「Leaflet」にcluster機能を追加する)

Leafletにはデフォルトのアイコンがあるのですが、それを自分で指定したアイコンで地図上に表示する方法を書いていきます。まぁそれだけは面白くないので、ドラゴンボールの筋斗雲がいまどこにいるか確認できるようなマップを作っていきましょう。

img

地図を用意

詳しくは、僕の前回の記事 (地図ライブラリの本命「Leaflet」を5分で理解&導入する)をみてください。本記事では詳しく説明はしません。

var mymap = L.map('mapid').setView([35.681167, 139.767052], 15);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
}).addTo(mymap);

そしてアイコンを用意

まずはよくあるクラウドのアイコンを黄色にしてダウンロードします。
kintoun.png ← こんな感じのやつ

「Leaflet」上でサイズなどを定義

var kintounIcon = L.icon({
    iconUrl: 'kintoun.png',
    iconSize: [30, 30],
    iconAnchor: [15, 30],
    popupAnchor: [0, -40]
});

iconAnchorはアイコンと、地図が接する点を定義するためのプロパティなのですが、基本的には、1番目はiconSizeのWidthの半分、2番目はiconSizeのHeightと同じ値を指定してあげればいいです。これをちゃんと設定しないと、地図をズームとかしたときにアイコンの位置がずれてしまうので気をつけましょう。

地図上にランダムに配置

あとは、前回同様、ランダムに地図上に配置してあげましょう。

for (var i = 0; i < 15; i++) {
    var marker = L.marker([35.681167 + (Math.random() / 50), 139.767052 + (Math.random() / 50)], {icon: kintounIcon});
    marker.bindPopup("<b>筋斗雲" + i + "</b>");
    marker.addTo(mymap);
}

image.png

できた。が・・・クソ微妙・・・黄色だから見えにくいし、筋斗雲なのに浮いてる感がない!影をつけましょう。

影をつける

まずは影の画像を用意して筋斗雲アイコンに反映します。
shadow.png ← こんな感じのやつ

var kintounIcon = L.icon({
    iconUrl: 'kintoun.png',
    shadowUrl: 'shadow.png',
    iconSize: [30, 30],
    shadowSize: [30, 30],
    iconAnchor: [15, 30],
    shadowAnchor: [15, 0],
    popupAnchor: [0, -40]
});

image.png

おーだいぶんいい感じになった!かなり浮いてる感でた(笑)
こんな感じで街中に筋斗雲が待機してて、UBERみたいにスマホで呼べたら最高ですね。
今回の記事は以上です。

12
7
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
12
7