我正在尝试使用谷歌方向API在mapview上绘制路线。我使用的解决方案从堆栈溢出本身,但我得到了一些关于初始化错误。
方向路线将是相同的谷歌Map本身或直线之一?
我应该在哪里调用这些方法呢?
我得到的错误是:
无法使用类型为“(coordinate:字符串,字符串,坐标:字符串,字符串)'
下面是代码:
func getRouteSteps(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {
let session = URLSession.shared
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(lat),\(long)&destination=\(directionlat),\(directionlong)&sensor=false&mode=driving&key=\(API KEY)")!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
guard error == nil else {
print(error!.localizedDescription)
return
}
guard let jsonResult = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] else {
print("error in JSONSerialization")
return
}
guard let routes = jsonResult!["routes"] as? [Any] else {
return
}
guard let route = routes[0] as? [String: Any] else {
return
}
guard let legs = route["legs"] as? [Any] else {
return
}
guard let leg = legs[0] as? [String: Any] else {
return
}
guard let steps = leg["steps"] as? [Any] else {
return
}
for item in steps {
guard let step = item as? [String: Any] else {
return
}
guard let polyline = step["polyline"] as? [String: Any] else {
return
}
guard let polyLineString = polyline["points"] as? String else {
return
}
//Call this method to draw path on map
DispatchQueue.main.async {
self.drawPath(from: polyLineString)
}
}
})
task.resume()
}
函数来绘制图形:
func drawPath(from polyStr: String){
let mapView: GMSMapView
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.map = mapView // Google MapView
//
let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: "\(lat)","\(long)", coordinate: "\(directionlat)","\(directionlong)")) as? [String : AnyObject]
mapView.moveCamera(cameraUpdate)
let currentZoom = mapView.camera.zoom
mapView.animate(toZoom: currentZoom - 1.4)
}
2条答案
按热度按时间iqih9akk1#
GMSCoordinatesBounds
将CLLocationCoordinates2D
类型作为参数,而不是String
。取代
与
一旦你把mapView添加到你的视图控制器中并得到坐标,调用你的函数
4xrmg8kj2#
你可以试试这个,用下面的方法来获取方向:
使用此选项在Map上绘制路线:
这是
MapModel
我希望你熟悉
Codables
,而且,当我收到点时,我已经调用了drawRoute
函数。