1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

フロント地図について:一番近い道の計算方法

Posted at

trufライブラリ

まず truf という地図空間処理ライブラリを紹介します。このライブラリを利用することで、一番近い道を探すことが可能です。

導入方法

npm install @turf/turf
import * as turf from '@turf/turf';

部分機能紹介

2点間の距離を計算
turf.distance(point1, point2)

点を作成
turf.point([longitude, latitude])

面積「めんせき」を計算
turf.area(polygon)

点が多辺形「たへんけい」内に存在するか判断
turf.booleanPointInPolygon(point, polygon)

一番近い点を探すコード例

以下のデータを例に挙げてみます:

const matchingFeatures =  
[[286.46939463294326, 49.9859483543],[256.46939463294326, 49.9859483543],[287.46939463294326, 49.9859483543]];  
let nowCoords = [321.1234, 12.1234]; // 現在の位置  
let minDistance = Infinity; // 無限大で初期化  
let entry = null;  // 最も近い位置を保存する変数  

matchingFeatures.forEach(feature => {  
    const dist = turf.distance(turf.point(nowCoords), turf.point(feature));  
    if (dist < minDistance) {  
        entry = feature;  
        minDistance = dist;  
    }  
});  

return entry;  

コードの説明

初期化
Infinity(正の無限大)を使って、どの数値よりも大きい初期値を設定します。

let minDistance = Infinity;
ループ処理
matchingFeaturesの各点について、現在地との距離をturk.distanceで計算し、最短距離を更新します。

比較
計算した距離が現在の最短距離より小さい場合、保存された値を更新します。

結果の取得
最後に、entryに最も近い点が格納されます。

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?