You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

KMM项目中替代Math.toRadians的Kotlin方案及球面距离计算

在KMM项目中实现无Java依赖的Haversine距离计算

Kotlin跨平台替代Java Math.toRadians的方案

Kotlin标准库提供了**kotlin.math.toRadians**函数,这是跨平台等价于Java Math.toRadians 的实现,属于Kotlin核心标准库,可在KMM的所有目标平台(JVM、iOS、Android等)上使用,完全不依赖Java类库。

同时,原代码中用到的其他Java Math方法(如pow、sin、cos等),也都有对应的Kotlin跨平台替代函数,全部位于kotlin.math包下。

修改后的无依赖实现代码

import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.math.toRadians

// 假设Geo类定义如下(可根据实际项目调整)
data class Geo(val lat: Double, val lon: Double)

internal class DistanceCalculator(private val lat: Double, private val lon: Double) {

    companion object {
        const val earthRadiusKm: Double = 6372.8
    }

    /**
     * Haversine公式:计算球面上两点间的大圆距离
     * 基于球面三角学中的半正矢定律,用于从经纬度计算两点间的最短球面距离
     *
     * @return 两点间距离(单位:千米)
     */
    fun haversine(destination: Geo): Double {
        val dLat = toRadians(destination.lat - this.lat)
        val dLon = toRadians(destination.lon - this.lon)
        val originLat = toRadians(this.lat)
        val destinationLat = toRadians(destination.lat)

        val a = sin(dLat / 2).pow(2) + sin(dLon / 2).pow(2) * cos(originLat) * cos(destinationLat)
        val c = 2 * asin(sqrt(a))
        return earthRadiusKm * c
    }
}

关键修改说明

  • 替换所有Math.xxx调用为kotlin.math包下的对应函数,确保跨平台兼容性
  • 使用Kotlin扩展函数语法(如sin(dLat/2).pow(2))替代Math.pow(Math.sin(...), ...),代码更简洁
  • 移除不必要的类型转换(如2.toDouble(),kotlin.math.pow支持自动推导Double类型参数)

内容的提问来源于stack exchange,提问作者Pablo R.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:17:52