2017-02-09 2 views

ответ

11

Чтобы нарисовать ломаную линию между двумя маркерами на GoogleMap в Swift 3.

// Pass your source and destination coordinates in this method. 
    func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){ 

      let config = URLSessionConfiguration.default 
      let session = URLSession(configuration: config) 

      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 
       if error != nil { 
        print(error!.localizedDescription) 
       }else{ 
        do { 
         if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{ 

          let routes = json["routes"] as? [Any] 
          let overview_polyline = routes?[0] as?[String:Any] 
          let polyString = overview_polyline?["points"] as?String 

          //Call this method to draw path on map 
          self.showPath(polyStr: polyString!) 
         } 

        }catch{ 
         print("error in JSONSerialization") 
        } 
       } 
      }) 
      task.resume() 
     } 

Чтобы нарисовать ломаную линию на карте.

func showPath(polyStr :String){ 
     let path = GMSPath(fromEncodedPath: polyStr) 
     let polyline = GMSPolyline(path: path) 
     polyline.strokeWidth = 3.0 
     polyline.map = mapView // Your map view 
    } 
+1

Я ценю хороший ответ –

+1

Ваш код работает как шарм. Большое спасибо :) –

+0

URL-адрес должен быть https, если вы используете авторизованный ключ –

12

Показаны многовидовых маршруты между двумя точками на картах Google в быстрой 3.0 с камерой зумом:

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() 
+1

Ницца .. Работает как шарм. –

+0

@sagar sukode Можем ли мы нарисовать только один маршрут. – Akhtar

0

Этот фрагмент кода будет работать для вас. Не забудьте изменить свой ключ и режим API (ходьба, вождение).

func draw(src: CLLocationCoordinate2D, dst: CLLocationCoordinate2D){ 

    let config = URLSessionConfiguration.default 
    let session = URLSession(configuration: config) 

    let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(src.latitude),\(src.longitude)&destination=\(dst.latitude),\(dst.longitude)&sensor=false&mode=walking&key=**YOUR_KEY**")! 

    let task = session.dataTask(with: url, completionHandler: { 
     (data, response, error) in 
     if error != nil { 
      print(error!.localizedDescription) 
     } else { 
      do { 
       if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] { 

        let preRoutes = json["routes"] as! NSArray 
        let routes = preRoutes[0] as! NSDictionary 
        let routeOverviewPolyline:NSDictionary = routes.value(forKey: "overview_polyline") as! NSDictionary 
        let polyString = routeOverviewPolyline.object(forKey: "points") as! String 

        DispatchQueue.main.async(execute: { 
         let path = GMSPath(fromEncodedPath: polyString) 
         let polyline = GMSPolyline(path: path) 
         polyline.strokeWidth = 5.0 
         polyline.strokeColor = UIColor.green 
         polyline.map = mapView  
        }) 
       } 

      } catch { 
       print("parsing error") 
      } 
     } 
    }) 
    task.resume() 
} 
0
Create a new Swift file copy this code, that's it call then drawPolygon() method from map view for polygon line. 



import GoogleMaps 

private struct MapPath : Decodable{ 

    var routes : [Route]? 

} 

private struct Route : Decodable{ 

    var overview_polyline : OverView? 
} 

private struct OverView : Decodable { 

    var points : String? 
} 



extension GMSMapView { 

    //MARK:- Call API for polygon points 

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

     let config = URLSessionConfiguration.default 
     let session = URLSession(configuration: config) 

     guard let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=false&mode=driving") else { 
      return 
     } 

     DispatchQueue.main.async { 

      session.dataTask(with: url) { (data, response, error) in 

       guard data != nil else { 
        return 
       } 

       do { 

        let route = try JSONDecoder().decode(MapPath.self, from: data!) 

        if let points = route.routes?.first?.overview_polyline?.points { 
         self.drawPath(with: points) 
        } 

        print(route.routes?.first?.overview_polyline?.points) 

       } catch let error { 

        print("Failed to draw ",error.localizedDescription) 
       } 


       }.resume() 


     } 


    } 

    //MARK:- Draw polygon 

    private func drawPath(with points : String){ 

     DispatchQueue.main.async { 

      let path = GMSPath(fromEncodedPath: points) 
      let polyline = GMSPolyline(path: path) 
      polyline.strokeWidth = 3.0 
      polyline.strokeColor = .red 
      polyline.map = self 

     } 

    } 



} 
Смежные вопросы