在ios方向路线上的谷歌地图在swift中无法正常工作

时间:2018-05-21 14:55:53

标签: ios swift google-maps-direction-api google-maps-sdk-ios

我正在尝试为两个位置绘制方向路线。我使用此功能进行路由。问题是它的dosnt适用于之前绘制的位置。即使我关闭应用程序并再次运行但是它可以用于以前一旦我改变给定的纬度或经度它就适用于新路线!任何想法?

func route(){
let origin = "35.6800,51.3819"
let destination = "35.6820,51.3769"

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

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({
                     var route = routes[0] as! NSDictionary

          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()
}

1 个答案:

答案 0 :(得分:1)

添加此变量以使用代码

var arrayPolyline = [GMSPolyline]()
var selectedRought:String!

func LoadMapRoute()
{
    let origin = "35.6800,51.3819"
    let destination = "35.6820,51.3769"

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

    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 arrRouts = json["routes"] as! NSArray

                for  polyline in self.arrayPolyline
                {
                    polyline.map = nil;
                }

                self.arrayPolyline.removeAll()

                let pathForRought:GMSMutablePath = GMSMutablePath()

                if (arrRouts.count == 0)
                {
                    let distance:CLLocationDistance = CLLocation.init(latitude: self.source.latitude, longitude: self.source.longitude).distance(from: CLLocation.init(latitude: self.destination.latitude, longitude: self.destination.longitude))

                    pathForRought.add(self.source)
                    pathForRought.add(self.destination)

                    let polyline = GMSPolyline.init(path: pathForRought)
                    self.selectedRought = pathForRought.encodedPath()
                    polyline.strokeWidth = 5
                    polyline.strokeColor = UIColor.blue
                    polyline.isTappable = true

                    self.arrayPolyline.append(polyline)

                    if (distance > 8000000)
                    {
                        polyline.geodesic = false
                    }
                    else
                    {
                        polyline.geodesic = true
                    }

                    polyline.map = self.mapView;
                }
                else
                {
                    for (index, element) in arrRouts.enumerated()
                    {
                        let dicData:NSDictionary = element as! NSDictionary

                        let routeOverviewPolyline = dicData["overview_polyline"] as! NSDictionary

                        let path =  GMSPath.init(fromEncodedPath: routeOverviewPolyline["points"] as! String)

                        let polyline = GMSPolyline.init(path: path)

                        polyline.isTappable = true

                        self.arrayPolyline.append(polyline)

                        polyline.strokeWidth = 5

                        if index == 0
                        {
                            self.selectedRought = routeOverviewPolyline["points"] as? String

                            polyline.strokeColor = UIColor.blue;
                        }
                        else
                        {
                            polyline.strokeColor = UIColor.darkGray;
                        }

                        polyline.geodesic = true;
                    }

                    for po in self.arrayPolyline.reversed()
                    {
                        po.map = self.mapView;
                    }
                }

                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5)
                {
                    let bounds:GMSCoordinateBounds = GMSCoordinateBounds.init(path: GMSPath.init(fromEncodedPath: self.selectedRought)!)

                    self.mapView.animate(with: GMSCameraUpdate.fit(bounds))
                }
            }
            catch let error as NSError
            {
                print("error:\(error)")
            }
        }
    }).resume()
}