在这里,折线编码:JavaScript->迅速 [英] HERE Polyline Encoding: JavaScript -> Swift

查看:57
本文介绍了在这里,折线编码:JavaScript->迅速的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Swift中实现HERE的Java代码折线编码算法(请参见下文).我已经在网上搜索过,还没有找到该算法的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 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吗?

Is there someone who can help convert this to Swift?

有关算法的详细信息,请参见此处:

Details of the algorithm may be found here:

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

预先感谢您的帮助,

Jason

推荐答案

我知道了:

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-&gt;迅速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆