我正在尝试使用 Google Direction API 在地图视图上绘制路线。我正在使用 Stack Overflow 本身的解决方案,但我收到了一些有关初始化程序的错误。
路线会与 Google 地图本身相同还是直线路线?
我应该在哪里调用这个方法?
我收到的错误为:
无法使用类型为“(坐标:字符串,字符串,坐标: 字符串,字符串)'
以下是代码:
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)
}
GMSCoordinatesBounds
采用 CLLocationCoordinates2D
类型作为参数,而不是 String
。
更换
let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: "\(lat)","\(long)", coordinate: "\(directionlat)","\(directionlong)")) as? [String : AnyObject]
与
let cameraUpdate = GMSCameraUpdate.fit(GMSCoordinateBounds(coordinate: CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long)), coordinate: CLLocationCoordinate2D(latitude: Double(directionlat), longitude: Double(directionlat))))
将mapView添加到视图控制器并获取坐标后,调用您的函数
self.getRouteSteps(from source: CLLocationCoordinate2D(latitude: Double(lat), longitude: Double(long)), destination: CLLocationCoordinate2D(latitude: Double(directionlat), longitude: Double(directionlat)))
您可以尝试一下,使用以下方法获取方向:
//This function is used to fetch the directions from origin to destination
private func fetchDirection(destinationLat: CLLocationDegrees, destinationLong: CLLocationDegrees) {
//Here you need to set your origin and destination points and mode
if let location = locationManager.location {
guard let url = URL(string: "\("https://maps.googleapis.com/maps/api/directions/json")?origin=\(location.coordinate.latitude),\(location.coordinate.longitude)&destination=\(destinationLat),\(destinationLong)&key=\(Constants.MapKey)") else { return }
let task = URLSession.shared.dataTask(with: url) { [unowned self](data, response, error) -> Void in
do {
guard let data = data else { return }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
guard let mapData = try? decoder.decode(MapModel.self, from: data) else { return }
if let points = mapData.routes.first?.overviewPolyline.points {
self.drawRoute(points: points)
}
}
}
task.resume()
}
}
用它在地图上绘制路线:
//This function is used to draw the routes
private func drawRoute(points: String) {
let path = GMSPath.init(fromEncodedPath: points)
let singleLine = GMSPolyline.init(path: path)
self.polylines.append(singleLine)
singleLine.strokeWidth = 6.0
let gradientColor: GMSStrokeStyle = GMSStrokeStyle.gradient(from: .red, to: .blue)
singleLine.spans = [GMSStyleSpan.init(style: gradientColor)]
if self.polylines.count > 0 {
self.polylines.forEach{ $0.map = nil }
}
singleLine.map = self.mapView
}
而且,这是
MapModel
struct MapModel: Decodable {
let status: String
let routes: [Routes]
}
struct Routes: Decodable {
let overviewPolyline: OverviewPolyline
}
struct OverviewPolyline: Decodable {
let points: String
}
我希望你熟悉
Codables
,而且,当我收到积分时,我已经调用了drawRoute
函数。