嗚嗚喔學習筆記: 十一月 2015

搜尋此網誌

2015年11月3日 星期二

計算GPS 距離 (Lua版本)

程式碼:

    local cos = math.cos
    local sin = math.sin
    local pi = math.pi
    local sqrt = math.sqrt
    local min = math.min
    local asin = math.asin
    local abs = math.abs

    -- Calculate distance
    function Distance(from, to)
        local distance = 0
        local radius = 6367000
        local radian = pi / 180
        local deltaLatitude = sin(radian * (from.latitude - to.latitude) /2)
        local deltaLongitude = sin(radian * (from.longitude - to.longitude) / 2)

        local circleDistance = 2 * asin(min(1, sqrt(deltaLatitude * deltaLatitude +
            cos(radian * from.latitude) * cos(radian * to.latitude) * deltaLongitude * deltaLongitude)))
            distance = abs(radius * circleDistance)
        return distance
    end