如何在 google 地图上画线

How to draw line on google maps

我有很多来自服务器的用户坐标,我想画线连接 this

我尝试使用 This way 但我的应用程序崩溃了,我猜这是因为我发送了太多请求。

最简单的方法是使用GMSPolyline.

假设您有 coordinatesCLLocationCoordinate2D 数组并且它们的顺序正确。

let path = GMSMutablePath()
for coord in coordinates {
    path.add(coord)
}
let line = GMSPolyline(path: path)
line.strokeColor = UIColor.blue
line.strokeWidth = 3.0
line.map = self.map

- Swift 4 个分机

用坐标创建路径:

extension GMSMutablePath {
    convenience init(coordinates: [CLLocationCoordinate2D]) {
        self.init()
        for coordinate in coordinates {
            add(coordinate)
        }
    }
}

添加地图路径:

extension GMSMapView {
    func addPath(_ path: GMSPath, strokeColor: UIColor? = nil, strokeWidth: CGFloat? = nil, geodesic: Bool? = nil, spans: [GMSStyleSpan]? = nil) {
        let line = GMSPolyline(path: path)
        line.strokeColor = strokeColor ?? line.strokeColor
        line.strokeWidth = strokeWidth ?? line.strokeWidth
        line.geodesic = geodesic ?? line.geodesic
        line.spans = spans ?? line.spans
        line.map = self
    }
}

用法:

let path = GMSMutablePath(coordinates: [<#Coordinates#>])
mapView.addPath(path)