Swift:如何将经纬度列表编码为Polyline并在地图上展示路径?
在Google Maps iOS SDK中展示经纬度路径的两种方法
嗨,很高兴能帮你解决这个问题!针对你的需求,我整理了两种实用的方案,不管是直接展示路径,还是把经纬度列表转成编码的Polyline字符串,都能轻松搞定:
一、直接用经纬度列表在地图上展示路径
这是最直接的方式,不需要先转成编码的Polyline,直接通过GMSMutablePath构建路径,再生成折线:
步骤示例(Swift代码):
- 先准备你的经纬度数组,比如:
let coordinates = [ CLLocationCoordinate2D(latitude: 39.9042, longitude: 116.4074), // 北京 CLLocationCoordinate2D(latitude: 31.2304, longitude: 121.4737), // 上海 CLLocationCoordinate2D(latitude: 23.1291, longitude: 113.2644) // 广州 ]
- 创建可变路径对象,逐个添加坐标:
let path = GMSMutablePath() for coordinate in coordinates { path.add(coordinate) }
- 创建折线并添加到地图上:
let polyline = GMSPolyline(path: path) polyline.strokeColor = .blue polyline.strokeWidth = 3.0 polyline.map = yourMapView // 替换成你的GMSMapView实例
这样就能在地图上看到一条连接所有经纬度的蓝色折线啦。
二、将经纬度列表转换为编码的Polyline字符串
如果你需要把经纬度列表转成编码的Polyline字符串(比如用于网络传输、存储,或者配合GMSPath(fromEncodePath:)使用),可以实现Google的Polyline编码算法。下面是一个Swift的实现示例:
编码函数:
func encodePolyline(coordinates: [CLLocationCoordinate2D]) -> String { var result = "" var lastLatitude: Int = 0 var lastLongitude: Int = 0 for coordinate in coordinates { let latitude = Int(round(coordinate.latitude * 1e5)) let longitude = Int(round(coordinate.longitude * 1e5)) let deltaLatitude = latitude - lastLatitude let deltaLongitude = longitude - lastLongitude result += encode(value: deltaLatitude) result += encode(value: deltaLongitude) lastLatitude = latitude lastLongitude = longitude } return result } private func encode(value: Int) -> String { var value = value var encoded = "" value = value << 1 if value < 0 { value = ~value } while value >= 0x20 { encoded += String(UnicodeScalar((0x20 | (value & 0x1F)) + 63)!) value = value >> 5 } encoded += String(UnicodeScalar(value + 63)!) return encoded }
使用示例:
let encodedPolyline = encodePolyline(coordinates: coordinates) // 现在你可以用这个编码字符串创建GMSPath if let path = GMSPath(fromEncodedPath: encodedPolyline) { let polyline = GMSPolyline(path: path) polyline.map = yourMapView }
小提示
- 如果你的经纬度数据量很大,建议使用编码后的Polyline,因为它的字符串体积更小,传输和存储更高效。
- 可以自定义折线的颜色、宽度,甚至添加虚线样式(通过
strokePattern属性),让路径更符合你的UI需求。
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

