ios - ios 方向 route 的谷歌地图无法在 swift 中正常工作

标签 ios swift google-directions-api google-maps-sdk-ios

我正在尝试为两个位置绘制方向路线。我使用此函数进行路线。问题是它不适用于之前绘制的位置。即使我关闭应用程序并再次运行,但它不适用于之前绘制的位置一旦我更改给定的纬度或经度坐标,它就适用于新路线!有什么想法吗?

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

最佳答案

添加此变量以使用代码

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

关于ios - ios 方向 route 的谷歌地图无法在 swift 中正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50451468/

相关文章:

swift - Xcode 13 中的 Info.plist 在哪里? (丢失,不在项目导航器内)

php - 使用 Google Map API v3 提供的 DirectionsService 查找并显示最近标记的路线

android - 使用 Mapbox SDK 在 Android 中实现逐向导航

iphone - Google direction api 请求在 ios5 中无效

ios - Xcode 在 Assets 目录打开时卡住

ios - django swift登录系统

iOS - 带有触摸事件的自定义 View

ios - AVAudioSession 无法识别来自蓝牙设备的音频

ios - 调整 UITableView 高度(嵌入在 UIScrollView 中)

ios - 以编程方式更改 UIStackView 中 1 个 subview 的大小