Polyline in GoogleMaps (swift)

  func callWebService(){
        
        let url = NSURL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(18.5235),\(73.7184)&destination=\(18.7603),\(73.8630)&key=AIzaSyDxSgGQX6jrn4iq6dyIWAKEOTneZ3Z8PtU")
        let request = NSURLRequest(URL: url!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: config)
        
        let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
            
            // notice that I can omit the types of data, response and error
            do{
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
                    
                    //print(jsonResult)
                    
                    let routes = jsonResult.valueForKey("routes")
                    //print(routes)
                    
                    let overViewPolyLine = routes![0]["overview_polyline"]!!["points"] as! String
                    print(overViewPolyLine)
                    
                    if overViewPolyLine != ""{
                        
                        //Call on Main Thread
                        dispatch_async(dispatch_get_main_queue()) {
                            
                            self.addPolyLineWithEncodedStringInMap(overViewPolyLine)
                        }
                        
                        
                    }
                    
                }
            }
            catch{
                
                print("Somthing wrong")
            }
        });
        
        // do whatever you need with the task e.g. run
        task.resume()
    }
    
    func addPolyLineWithEncodedStringInMap(encodedString: String) {
        
        
        let camera = GMSCameraPosition.cameraWithLatitude(18.5204, longitude: 73.8567, zoom: 10.0)
        let mapView = GMSMapView.mapWithFrame(self.homeMapView.bounds, camera: camera)
        mapView.myLocationEnabled = true
        
        let path = GMSMutablePath(fromEncodedPath: encodedString)
        let polyLine = GMSPolyline(path: path)
        polyLine.strokeWidth = 5
        polyLine.strokeColor = UIColor.yellowColor()
        polyLine.map = mapView
        
        let smarker = GMSMarker()
        smarker.position = CLLocationCoordinate2D(latitude: 18.5235, longitude: 73.7184)
        smarker.title = "Lavale"
        smarker.snippet = "Maharshtra"
        smarker.map = mapView
        
        let dmarker = GMSMarker()
        dmarker.position = CLLocationCoordinate2D(latitude: 18.7603, longitude: 73.8630)
        dmarker.title = "Chakan"
        dmarker.snippet = "Maharshtra"
        dmarker.map = mapView
        
        self.homeMapView .addSubview(mapView)
        

    }
Previous
Next Post »