SWIFT: google maps draw waypoint polyline

前端 未结 4 1876
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 09:12

Hi I wonder if there is a method to draw a waypoint between two or more markers in google maps iOS. I don\'t want to draw straight lines... but use just public roads. Here i

相关标签:
4条回答
  • 2021-01-07 09:55
       let point3 = CLLocationCoordinate2D(latitude: Double(30.7173), longitude: Double(76.8329))
    
      let point4 = CLLocationCoordinate2D(latitude: Double(30.6942), longitude: Double(76.8606))
        let point5 = CLLocationCoordinate2D(latitude: Double(30.7465), longitude: Double(76.7872))
       var arrOfWayPoints : NSMutableArray = NSMutableArray()
                                        arrOfWayPoints.insert(point3, at: 0)
    
                                        arrOfWayPoints.insert(point4, at: 1)
    
                                        arrOfWayPoints.insert(point5, at: 2)
    
    
    
                                        self.drawRouteWithWaypoint(positions: arrOfWayPoints as! [CLLocationCoordinate2D])
    
     static var distance = Double()
    
    
        func drawRouteWithWaypoint(positions:[CLLocationCoordinate2D]) {
            LiveJob.getDotsToDrawRoute(positions: positions, completion: { path in
                //self.route.countRouteDistance(p: path)
                self.polyline.path = path
                self.polyline.strokeColor = UIColor.blue
                self.polyline.strokeWidth = 2.0
                self.polyline.map = self.mapView
            })
    
            self.lblDistance.text = String(LiveJob.distance)
        }
    
        static func getDotsToDrawRoute(positions : [CLLocationCoordinate2D], completion: @escaping(_ path : GMSPath) -> Void) {
            if positions.count > 1 {
                let origin = positions.first
                let destination = positions.last
                var wayPoints = ""
                for point in positions {
                    wayPoints = wayPoints.characters.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)|\(point.latitude),\(point.longitude)"
    
                }
                let request = "https://maps.googleapis.com/maps/api/directions/json"
                let parameters : [String : String] = ["origin" : "\(origin!.latitude),\(origin!.longitude)", "destination" : "\(destination!.latitude),\(destination!.longitude)", "wayPoints" : wayPoints,"mode" : "Transit","key" : "AIzaSyCtMHyxPEModWK8IgzBD96hQMFL-UCIjcY"]
                Alamofire.request(request, method:.get, parameters : parameters).responseJSON(completionHandler: { response in
                    guard let dictionary = response.result.value as? [String : AnyObject]
                        else {
                            return
                    }
                    if let routes = dictionary["routes"] as? [[String : AnyObject]] {
                        if routes.count > 0 {
                            var first = routes.first
                            if let legs = first!["legs"] as? [[String : AnyObject]] {
    
                                let newLeg = legs[0]
                                let distance = newLeg["distance"]
                               // LiveJob.distance =  LiveJob.distance + distance!.doubleValue
    
    
    
                                let fullPath : GMSMutablePath = GMSMutablePath()
                                for leg in legs {
                                    if let steps = leg["steps"] as? [[String : AnyObject]] {
                                        for step in steps {
                                            if let polyline = step["polyline"] as? [String : AnyObject] {
                                                if let points = polyline["points"] as? String {
                                                    fullPath.appendPath(path: GMSMutablePath(fromEncodedPath: points))
                                                }
                                            }
                                        }
                                        completion(fullPath)
                                    }
                                }
                            }
                        }
                    }
                })
            }
        }
    
    0 讨论(0)
  • 2021-01-07 09:56
    private func drowRoute(){
    
    let path = GMSMutablePath()
        path.addLatitude(self.lat!, longitude: self.long!)
        path.addLatitude(self.destLat!, longitude: self.destLong!)
    let polyline = GMSPolyline(path: path)
    polyline.strokeWidth = 2.0
    polyline.strokeColor = UIColor.blue
    polyline.geodesic = true
    polyline.map = mappView
    
    }
    
    0 讨论(0)
  • 2021-01-07 09:58

    To draw polyline between two markers on GoogleMap in 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()
        }
    

    To draw polyline on map .

    func showPath(polyStr :String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.map = mapView // Your map view
    }
    
    0 讨论(0)
  • 2021-01-07 10:08

    To draw polylines between points two ore more you should use google map request read this link https://developers.google.com/maps/documentation/directions/intro#Waypoints in my case i did

        func drawRoute() {
        ServerCommunicator.getDotsToDrawRoute(positions: positions, completion: { path in
            self.route.countRouteDistance(p: path)
            self.polyline.path = path
            self.polyline.strokeColor = UserSession.tintColor
            self.polyline.strokeWidth = 4.0
            self.polyline.map = self._mapView
        })
    }
    

    and the part with request

    static func getDotsToDrawRoute(positions : [CLLocationCoordinate2D], completion: @escaping(_ path : GMSPath) -> Void) {
        if positions.count > 1 {
            let origin = positions.first
            let destination = positions.last
            var wayPoints = ""
            for point in positions {
                wayPoints = wayPoints.characters.count == 0 ? "\(point.latitude),\(point.longitude)" : "\(wayPoints)|\(point.latitude),\(point.longitude)"
            }
            let request = "https://maps.googleapis.com/maps/api/directions/json"
            let parameters : [String : String] = ["origin" : "\(origin!.latitude),\(origin!.longitude)", "destination" : "\(destination!.latitude),\(destination!.longitude)", "wayPoints" : wayPoints, "key" : googleAPI_KEY]
            Alamofire.request(request, method:.get, parameters : parameters).responseJSON(completionHandler: { response in
                guard let dictionary = response.result.value as? [String : AnyObject]
                    else {
                        return
                }
                if let routes = dictionary["routes"] as? [[String : AnyObject]] {
                    if routes.count > 0 {
                        var first = routes.first
                        if let legs = first!["legs"] as? [[String : AnyObject]] {
                            let fullPath : GMSMutablePath = GMSMutablePath()
                            for leg in legs {
                                if let steps = leg["steps"] as? [[String : AnyObject]] {
                                    for step in steps {
                                        if let polyline = step["polyline"] as? [String : AnyObject] {
                                            if let points = polyline["points"] as? String {
                                                fullPath.appendPath(GMSMutablePath(fromEncodedPath: points))
                                            }
                                        }
                                    }
                                    completion(path: fullPath)
                                }
                            }
                        }
                    }
                }
            })
        }
    }
    extension GMSMutablePath {
    
    func appendPath(path : GMSPath?) {
        if let path = path {
            for i in 0..<path.count() {
                self.add(path.coordinate(at: i))
            }
        }
    }
    

    }

    0 讨论(0)
提交回复
热议问题