我在 iOS 上使用 swift 并使用 MKMapView。
我一直致力于为用户提供一个“从-到”文本字段,并让用户在“从”到“位置”之间拥有一种路线形式。我已经使用 Apple 的内置方向和地理编码 api 调用在 mkmapview 上进行了工作。然而使用一段时间后发现很多国家不支持苹果Apple - 支持的国家/地区的说明
那么有没有办法从 google 地图 SDK 获取路线并将其转换为 MKPolyline 或 MKOverlay?我没有使用过谷歌地图,所以请记住这一点。我看到这个问题iPhone:使用 Google 获取路线它有一个答案,但最新的解决方案已经有 4 年历史了,而且是 Objective-C 语言。虽然我确实了解如何将 Objective-C 代码转换为 swift,但我宁愿不必经历整个项目。请记住,这是一个更大项目的一部分,所以我无法将整个事情切换到谷歌地图。
I think 这个 Stackoverflow 答案可以将编码的折线转换为 MKPolyline。
答案是Objective-C版本,所以我尝试将其转换为Swift,示例代码:
func polyLineWithEncodedString(encodedString: String) -> MKPolyline {
let bytes = (encodedString as NSString).UTF8String
let length = encodedString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
var idx: Int = 0
var count = length / 4
var coords = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(count)
var coordIdx: Int = 0
var latitude: Double = 0
var longitude: Double = 0
while (idx < length) {
var byte = 0
var res = 0
var shift = 0
do {
byte = bytes[idx++] - 0x3F
res |= (byte & 0x1F) << shift
shift += 5
} while (byte >= 0x20)
let deltaLat = ((res & 1) != 0x0 ? ~(res >> 1) : (res >> 1))
latitude += Double(deltaLat)
shift = 0
res = 0
do {
byte = bytes[idx++] - 0x3F
res |= (byte & 0x1F) << shift
shift += 5
} while (byte >= 0x20)
let deltaLon = ((res & 1) != 0x0 ? ~(res >> 1) : (res >> 1))
longitude += Double(deltaLon)
let finalLat: Double = latitude * 1E-5
let finalLon: Double = longitude * 1E-5
let coord = CLLocationCoordinate2DMake(finalLat, finalLon)
coords[coordIdx++] = coord
if coordIdx == count {
let newCount = count + 10
let temp = coords
coords.dealloc(count)
coords = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(newCount)
for index in 0..<count {
coords[index] = temp[index]
}
temp.destroy()
count = newCount
}
}
let polyLine = MKPolyline(coordinates: coords, count: coordIdx)
coords.destroy()
return polyLine
}
您可以尝试以下示例项目这个 GitHub 链接.
下图是使用 Google Direction API Web 服务在 MKMapView 上渲染从旧金山到圣何塞的路线的图像。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)