Skip to content Skip to sidebar Skip to footer

Here Polyline Encoding: Javascript -> Swift

I am trying to implement HERE's Javascript polyline encoding algorithm (see below) in Swift. I have searched online and have not found a Swift version of this algorithm. function

Solution 1:

I figured it out:

func hereEncodeNumber(_ value: Double) -> [Character] {

    let ENCODING_CHARS : [Character] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9","-","_"]
    var result : [Character] = []

    // Convert value to fixed point
    let fixedPoint = (value * 100000).rounded(.toNearestOrAwayFromZero)

    // Convert fixed point to binary
    var binaryNum = Int32(exactly: fixedPoint)!

    // Make room on lowest bit
    binaryNum = binaryNum << 1

    // Flip bits of negative numbers and ensure that  last bit is set
    // (should actually always be case, but for readability it is ok to do it explicitly)
    if binaryNum < 0 {
        binaryNum = ~(binaryNum) | 0x01
    }

    // Var-length encode number in chunks of 5 bits starting with least significant
    // to most significant
    while binaryNum > 0x1F {
        result.append(ENCODING_CHARS[Int((binaryNum & 0x1F) | 0x20)])
        binaryNum >>= 5
    }
    result.append(ENCODING_CHARS[Int(binaryNum)])
    return result
}

Post a Comment for "Here Polyline Encoding: Javascript -> Swift"