gpt4 book ai didi

ios - 如何在谷歌地图 iOS swift 中绘制两个位置之间的路线

转载 作者:IT王子 更新时间:2023-10-29 05:45:25 40 4
gpt4 key购买 nike

我在我的 iOS swift 项目中使用谷歌地图。我想在 map 上的两个位置之间绘制一条路径(不是直线)。知道怎么做吗?

最佳答案

在 Swift 中在 Google map 上的两个位置之间绘制折线。

//在此方法中传递您的源坐标和目标坐标。

func fetchRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D) {

let session = URLSession.shared

let url = URL(string: "http://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving")!

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], let jsonResponse = jsonResult else {
print("error in JSONSerialization")
return
}

guard let routes = jsonResponse["routes"] as? [Any] else {
return
}

guard let route = routes[0] as? [String: Any] else {
return
}

guard let overview_polyline = route["overview_polyline"] as? [String: Any] else {
return
}

guard let polyLineString = overview_polyline["points"] as? String else {
return
}

//Call this method to draw path on map
self.drawPath(from: polyLineString)
})
task.resume()
}

在 map 上绘制折线。

func drawPath(from polyStr: String){
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.map = mapView // Google MapView
}

关于ios - 如何在谷歌地图 iOS swift 中绘制两个位置之间的路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42136203/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com