使用Swift 3在自定义视图中使用Google地图绘制折线

5 google-maps polyline ios swift3

我试图在自定义UIView上使用谷歌地图绘制两个地方之间的路线,但无法正确实施.我的自定义视图是mapViewX.我使用pods安装了google sdk,其中包括pod'GoogleMaps'和pod'GooglePlaces'.我将自定义视图类设为'GMSMapView'.我的代码是:

    @IBOutlet weak var mapViewX: GMSMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let path = GMSMutablePath()
    path.add(CLLocationCoordinate2D(latitude: 37.778483, longitude: -122.513960))
    path.add(CLLocationCoordinate2D(latitude: 37.706753, longitude: -122.418677))
    let polyline = GMSPolyline(path: path)
    polyline.strokeColor = .black
    polyline.strokeWidth = 10.0
    polyline.map = mapViewX

}
Run Code Online (Sandbox Code Playgroud)

请帮忙!

Muh*_*han 8

它在这里工作正常.确保您设置正确的坐标GMSCameraPosition.

编辑

要绘制两个坐标之间的路径,请使用 Google Maps Direction API

就像是 :

    let origin = "\(37.778483),\(-122.513960)"
    let destination = "\(37.706753),\(-122.418677)"
    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=[YOUR-API-KEY]"

    Alamofire.request(url).responseJSON { response in
        let json = JSON(data: response.data!)
        let routes = json["routes"].arrayValue

        for route in routes
        {
            let routeOverviewPolyline = route["overview_polyline"].dictionary
            let points = routeOverviewPolyline?["points"]?.stringValue
            let path = GMSPath.init(fromEncodedPath: points!)

            let polyline = GMSPolyline(path: path)
            polyline.strokeColor = .black
            polyline.strokeWidth = 10.0
            polyline.map = mapViewX

        }
    }
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Directions API Developer's Guide