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

Androidで目的地までの直線距離を取得する

0
Posted at

現在地から目的地までの距離を測る方法をメモします。
徒歩距離や車での移動距離を取得するには Google Routes API など有料サービスが必要ですが、直線距離であれば標準機能で計算できます。

やり方はLocation.distanceBetween()distanceTo()を使用します。

val results = FloatArray(1)

Location.distanceBetween(
    currentLat,
    currentLng,
    targetLat,
    targetLng,
    results
)

val distanceMeters = results[0]

計算結果は results[0] にメートル単位で格納されます。

サンプル

val results = FloatArray(1)
Location.distanceBetween(
    35.690299,
    139.700036, // 新宿駅
    35.658434,
    139.701310, // 渋谷駅
    results
)
val distanceMeters = results[0]

Log.d("距離", "${distanceMeters.toInt()}m") // 3537m

Location オブジェクトを生成して距離を求めることもできます。

val current = Location("current").apply {
    latitude = currentLat
    longitude = currentLng
}

val target = Location("target").apply {
    latitude = targetLat
    longitude = targetLng
}

val distanceMeters = current.distanceTo(target)

サンプル

val current = Location("current").apply {
    latitude = 35.658347
    longitude = 139.745269 // 東京タワー
}
val target = Location("target").apply {
    latitude = 35.710315
    longitude = 139.810175 // 東京スカイツリー
}
val distanceMeters = current.distanceTo(target)

Log.d("距離", "${distanceMeters.toInt()}m") // 8232m

簡易な距離を求めるのであれば標準機能で十分です。

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