javascript - HERE折线编码: JavaScript -> Swift

标签 javascript ios swift here-api here-maps-rest

我正在尝试在 Swift 中实现 HERE 的 Javascript 折线编码算法(见下文)。我在网上搜索过,但没有找到该算法的 Swift 版本。

function hereEncodeFloat(value) {
  var ENCODING_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
  var result = [];

  // convert to fixed point
  var fixedPoint = Math.round(value * 100000);

  // make room on the lowest bit
  fixedPoint = fixedPoint << 1;

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

  // var-length encode the number in chunks of 5 bits starting with the least significant
  // to the most significant
  while (fixedPoint > 0x1F) {
    result.push(ENCODING_CHARS[(fixedPoint & 0x1F) | 0x20]);
    fixedPoint >>= 5;
  }
  result.push(ENCODING_CHARS[fixedPoint]);
  return result.join('');
}

有人可以帮助将其转换为 Swift 吗?

算法的细节可以在这里找到:

https://developer.here.com/documentation/places/topics/location-contexts.html#location-contexts__here-polyline-encoding

预先感谢您的帮助,

杰森

最佳答案

我想通了:

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
}

关于javascript - HERE折线编码: JavaScript -> Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52595579/

相关文章:

javascript - 在 JavaScript 中的异步函数末尾运行同步函数?

JavaScript 错误 "MyIdentifier is not defined"

ios - ZBar 用于 iPad 中的横向方向

iphone - 像 UITableView 一样的 UIPickerView 索引?

javascript - 如何通过单击区域外部来隐藏当前内容,以及当我在 IE11 中显示其他内容时?

ios - 如何在 sd_setImageWithURL 加载的单元格中将 tintcolor 更改为 uiimage?

swift - 在 Swift 中使用 "fallthrough"关键字有什么问题?

ios - 尝试为 UITableViewCell 绘制虚线边框

Swift 表达式从 'Any??' 隐式强制转换为 'Any?'

javascript - 使用 pstricks 和 latex2html5 绘制圆弧