Search code examples
iosswiftgoogle-directions-apigoogle-maps-sdk-ios

Google map in ios direction route not work correctly in swift


I'm trying to draw direction route for two locations.I use this function to route.The problem is that it dosnt work for locations that were drawn before.even I close the app and run again but it dosnt work for previous coordinates as soon as I change the given lat or lon it works for new route! any idea?

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

Solution

  • Add this Variable to use code

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