画像




障害物を避けた最短経路を計算するメモ。




画像




script.js

// MIERUNE MONO読み込み
var map = new mapboxgl.Map({
container: "map",
style: {
version: 8,
sources: {
m_mono: {
type: "raster",
tiles: ["https://tile.mierune.co.jp/mierune_mono/{z}/{x}/{y}.png"],
tileSize: 256
}
},
layers: [{
id: "m_mono",
type: "raster",
source: "m_mono",
minzoom: 0,
maxzoom: 18
}]
},
center: [139.770, 35.676],
zoom: 13
});


map.on("load", function () {
// ライン取得
var line = turf.lineString([[139.7377, 35.6804], [139.7870, 35.6821]]);

// ライン表示
map.addSource("LineSample", {
type: "geojson",
data: line
});
map.addLayer({
id: "LineSample",
type: "line",
source: "LineSample",
layout: {
"line-join": "round",
"line-cap": "round"
},
paint: {
"line-color": "#1253A4",
"line-width": 5,
"line-opacity": 0.6
}
});

// ポリゴンを取得
var polygon = turf.polygon([[
[139.75536346435547, 35.67486854197016],
[139.7717571258545, 35.67486854197016],
[139.7717571258545, 35.68720867389012],
[139.75536346435547, 35.68720867389012],
[139.75536346435547, 35.67486854197016]
]]);

// ポリゴン表示
map.addSource("PolygonSample", {
type: "geojson",
data: polygon
});
map.addLayer({
id: "PolygonSample",
type: "fill",
source: "PolygonSample",
layout: {},
paint: {
"fill-color": "#1253A4",
"fill-opacity": 0.5
}
});
map.addLayer({
id: "PolygonLineSample",
type: "line",
source: "PolygonSample",
layout: {
"line-join": "round",
"line-cap": "round"
},
paint: {
"line-color": "#1253A4",
"line-width": 5,
"line-opacity": 0.8
}
});

// 障害物を避けた最短経路を計算
var start = [139.7377, 35.6804];
var end = [139.7870, 35.6821];
var options = {
obstacles: polygon
};
var path = turf.shortestPath(start, end, options);

// ライン表示
map.addSource("LineSample2", {
type: "geojson",
data: path
});
map.addLayer({
id: "LineSample2",
type: "line",
source: "LineSample2",
layout: {
"line-join": "round",
"line-cap": "round"
},
paint: {
"line-color": "#FFD464",
"line-width": 5,
"line-opacity": 0.6
}
});

});

// コントロール関係表示
map.addControl(new mapboxgl.NavigationControl());






Turf.jsを手軽に始めるビルド環境公開しています。
turfjs-starter







Q&A