Leafletで地図上に二点間の経路を線引してみよう


Leafletで位置情報をオブジェクトの形式で持つように変えてみようLeafletで地図上に線を引いてみようの内容を組み合わせて、二点間の移動経路を表示してみよう。


https://github.com/inunosinsi/Leaflet_OpenStreetMap_Sample/blob/main/9.htmlで作成したコードにコードを改修していきます。


let lines = [
	{
		"type": "LineString",
		"coordinates": [
			[135.76198, 35.02320], 
			[135.76198, 35.02116], 
			[135.76383, 35.02111], 
			[135.76394, 35.02013],
			[135.76426, 35.02009],
			[135.76464, 35.01976]
		]
	}
];

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

let objects = [
	{
		"type" : "Feature",
		"properties" : {
			"name" : "京都御苑",
			"url" : "https://www.openstreetmap.org/#map=17/"+lat+"/"+lng
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [lng, lat]	//注意:緯度経度の渡し方が逆になる
		}
	},
	{
		"type": "LineString",
		"coordinates": [
			[135.76198, 35.02320], 
			[135.76198, 35.02116], 
			[135.76383, 35.02111], 
			[135.76394, 35.02013],
			[135.76426, 35.02009],
			[135.76464, 35.01976]
		]
	},
	{
		"type" : "Feature",
		"properties" : {
			"name" : "富小路広場",
			"url" : "https://www.openstreetmap.org/#map=17/35.019229/135.765492"
		},
		"geometry" :  {
			"type": "Point",
			"coordinates" : [135.765492, 35.019229]
		}
	}
];

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

※今回は線(LineString)と地物(Feature)を合わせた配列になりますので、変数名をlinesからobjectsに変更しています。


位置情報の配列を作るに当たって、ピンを立てる為のFeatureと線を引く為のLineStringのオブジェクトを両方含めています。


地物(Feature)の場合は、geometryの値を持ち、その中でtypeをPointで指定したオブジェクト内でcoordinates(座標)を持つ事が重要で、線(LineString)の場合は、typeと同階層のプロパティでcoordinatesを持つことが重要になります。


これらの記述ルールはUsing GeoJSON with Leaflet - Leaflet - a JavaScript library for interactive mapsに記載されている内容を参考にしましょう。


今回のコードはhttps://github.com/inunosinsi/Leaflet_OpenStreetMap_Sample/blob/main/11.htmlになります。


追記

inunosinsiというアカウントで、オープンストリートマップに参加しています。

https://www.openstreetmap.org/user/inunosinsi

京都の東本願寺で開催されているプログラミング教室で講師をしています。
詳しくはTera schoolを御覧ください。
大阪府高槻市でプログラミング教室を開設しています。
同じカテゴリーの記事
マインクラフト用ビジュアルエディタを開発しています。

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