Leafletでカテゴリ分けをしてみよう


オブジェクト形式で複数の地物(feature)の情報をカテゴリ分けし、任意のカテゴリの地物のみピンを立ててみます。


今回の内容はLeafletで位置情報をオブジェクトの形式で持つように変えてみようhttps://github.com/inunosinsi/Leaflet_OpenStreetMap_Sample/blob/main/6.htmlのコードを改修します。


はじめに、下記のように地物をたくさん登録します。

let features = [
	{
		"type" : "Feature",
		"properties" : {
			"name" : "上賀茂神社",
			"category" : "shrine"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.75224, 35.06048]
		}
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "松尾大社",
			"category" : "shrine"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.685283, 35.000186]
		}
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "八坂神社",
			"category" : "shrine"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.778254, 35.003608]
		}
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "城南宮",
			"category" : "shrine"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.746952, 34.950646]
		}
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "二条城",
			"category" : "castle"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.747795, 35.014135]
		}
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "金閣寺",
			"category" : "temple"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.728440, 35.039529]
		}
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "銀閣寺",
			"category" : "temple"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.798032, 35.026549]
		}
	}
];

地物を登録する際にpropertiesでcategoryの値を追加しておきます。

今回はshirine(神社)、castle(城)とtemple(寺)の地物を追加しています。


続いて、

L.geoJSON(features).addTo(map);

L.geoJSON(features, {
	filter: function(feature, layer) {
		switch(feature.properties.category){
			case "shrine":
				return true;
			default:
				return false;
		}
	}
}).addTo(map);

に書き換えます。


コードを変更した後、ファイルをクリックしてブラウザ上で実行してみますと、shrine(神社)の地物のみピンが立ちます。


L.geoJSONの第一引数のオブジェクトで、filterで無名関数を指定すると、各地物のオブジェクトを順番に確認します。

無名関数内でtrue(真)を返すとピンが立ち、false(偽)を返すとピンは立ちません。


if文で地物毎のカテゴリ(category)を確認し、表示したいカテゴリの地物のみ、trueを返すように書くことで、任意の地物のみのピンを立てることができます。


今回のコードはhttps://github.com/inunosinsi/Leaflet_OpenStreetMap_Sample/blob/main/12.html

OpenStreetMapとLeafletの作品:土を理解する為の探求マップ

inunosinsiというアカウントで、オープンストリートマップに参加しています。
https://www.openstreetmap.org/user/inunosinsi
京都の東本願寺で開催されているプログラミング教室で講師をしています。
詳しくはTera schoolを御覧ください。
大阪府高槻市でプログラミング教室を開設しています。
同じカテゴリーの記事
マインクラフト用ビジュアルエディタを開発しています。

詳しくはinunosinsi/mcws_blockly - githubをご覧ください。