如何在Google地图iOS swift中的两个位置之间绘制路线 [英] How to draw routes between two locations in google maps iOS swift

查看:338
本文介绍了如何在Google地图iOS swift中的两个位置之间绘制路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using google maps in my iOS swift project. I want to draw a path between two locations on the map (Not straight line). Any idea how to do that ?

推荐答案

在google地图中的两个位置之间显示多路径 swift 3.0 with camera zoom

Showing Multiple-routes between two locations in google maps in swift 3.0 with camera zoom:

    let origin = "\(startLocation.coordinate.latitude),\(startLocation.coordinate.longitude)"
    let destination = "\(destinationLocation.coordinate.latitude),\(destinationLocation.coordinate.longitude)"

    let urlString = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=API_KEY"

    let url = URL(string: urlString)
    URLSession.shared.dataTask(with: url!, completionHandler: {
        (data, response, error) in
        if(error != nil){
            print("error")
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String : AnyObject]
                let routes = json["routes"] as! NSArray
                self.mapView.clear()

                OperationQueue.main.addOperation({
                    for route in routes
                    {
                        let routeOverviewPolyline:NSDictionary = (route as! NSDictionary).value(forKey: "overview_polyline") as! NSDictionary
                        let points = routeOverviewPolyline.object(forKey: "points")
                        let path = GMSPath.init(fromEncodedPath: points! as! String)
                        let polyline = GMSPolyline.init(path: path)
                        polyline.strokeWidth = 3

                        let bounds = GMSCoordinateBounds(path: path!)
                        self.mapView!.animate(with: GMSCameraUpdate.fit(bounds, withPadding: 30.0))

                        polyline.map = self.mapView

                    }
                })
            }catch let error as NSError{
                print("error:\(error)")
            }
        }
    }).resume()

这篇关于如何在Google地图iOS swift中的两个位置之间绘制路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆