Swift Google Maps GMS Marker not sticking on user location - swift

I have an issue with my GMSMarker, it seems that it does not stick on user location. I want to stick the marker to user location itself, check my code below.
func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
UpdateService.instance.updateUserLocation(withCoordinate: position.target)
UpdateService.instance.updateContractorLocation(withCoordinate: position.target)
}
func loadContractorAnnotation() {
DispatchQueue.main.async {
DataService.instance.REF_CONTRACTOR.observeSingleEvent(of: .value, with: { (snapshot) in
if let contractorSnapshot = snapshot.children.allObjects as? [DataSnapshot] {
for contractor in contractorSnapshot {
if contractor.hasChild("coordinate") {
if contractor.childSnapshot(forPath: "contractorIsAvailable").value as? Bool == true {
if let contractorCoordinateDict = contractor.value as? Dictionary<String, Any> {
let coordinateArray = contractorCoordinateDict["coordinate"] as! NSArray
let contractorCoordinate = CLLocationCoordinate2D(latitude: coordinateArray[0] as! CLLocationDegrees , longitude: coordinateArray[1] as! CLLocationDegrees)
CATransaction.begin()
CAAnimation.init().duration = 0.5
self.contractorMarker.position = contractorCoordinate
self.contractorMarker.iconView = self.markerImageView(image: UIImage(named: "contractor-marker")!, size: CGSize(width: 30, height: 30))
self.contractorMarker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
CATransaction.commit()
self.contractorMarker.map = self.mapView
}
}
}
}
}
})
}
}
// ViewDidLoad()
DataService.instance.REF_CONTRACTOR.observe(.value, with: {(snapshot) in
self.loadContractorAnnotation()
})
And it looks like whenever I drag my map it seems that it will follow the icon centered in my google map instead it will stick only on user location when i drag the google map. You can check it on this video that I upload.

My bad, It seems that I put everything on google map,
I moved the lines of code below from didChange position function.
UpdateService.instance.updateUserLocation(withCoordinate: position.target)
UpdateService.instance.updateContractorLocation(withCoordinate: position.target)
into this block of code.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

Related

custom Google Maps blue dot in Swift

What I want to achieve is to customize google maps blue dot with an svg icon,
with the icon moving when location is changed.
what I am doing:
struct GoogleMapsView: UIViewRepresentable {
#ObservedObject var locationManager = LocationManager.shared
#State var myLocationDot = GMSMarker()
#Binding var nearbyDrivers: [NearbyDriver]
init(nearbyDrivers: Binding<[NearbyDriver]>){
self._nearbyDrivers = nearbyDrivers
myLocationDot.position = locationManager.userLocation!.coordinate
}
func makeUIView(context: Context) -> GMSMapView {
let camera = GMSCameraPosition.camera(withLatitude: locationManager.userLocation!.coordinate.latitude, longitude: locationManager.userLocation!.coordinate.longitude, zoom: 15)
let mapView = GMSMapView(frame: CGRect.zero, camera: camera)
myLocationDot.position = CLLocationCoordinate2D(latitude: locationManager.userLocation!.coordinate.latitude, longitude: locationManager.userLocation!.coordinate.longitude)
let myLocationDotIcon = UIImage(named: "myLocationDotIcon.svg")
let myLocationDotIconImage = UIImageView(image: myLocationDotIcon!)
myLocationDotIconImage.frame = CGRect(x: 0, y: 0, width: 40, height: 50)
myLocationDot.iconView = myLocationDotIconImage
myLocationDot.zIndex = 1
myLocationDot.map = mapView
// MARK: - Load nearby drivers
if !nearbyDrivers.isEmpty {
for driver in nearbyDrivers {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: driver.location.lat, longitude: driver.location.long)
let locationIcon = UIImage(named: "carAnnotation.png")
let locationIconImage = UIImageView(image: locationIcon!)
locationIconImage.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
marker.iconView = locationIconImage
marker.zIndex = 0
marker.map = mapView
}
}
//MARK: - MapStyle
do {
if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
} else {
NSLog("Unable to find style.json")
}
} catch {
NSLog("One or more of the map styles failed to load. \(error)")
}
return mapView
}
func updateUIView(_ uiView: GMSMapView, context: Context) {
uiView.isMyLocationEnabled = false
}
func makeCoordinator() -> Coordinator {
Coordinator(myLocationDot: $myLocationDot, owner: self)
}
class Coordinator: NSObject, GMSMapViewDelegate, CLLocationManagerDelegate {
#ObservedObject var locationManager = LocationManager.shared
#Binding var myLocationDot: GMSMarker
let owner: GoogleMapsView
init(myLocationDot: Binding<GMSMarker>, owner: GoogleMapsView) {
self.owner = owner
_myLocationDot = myLocationDot
}
func didTapMyLocationButton(for mapView: GMSMapView) -> Bool {
mapView.animate(toLocation: locationManager.userLocation!.coordinate)
return true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
myLocationDot.position = locations.last!.coordinate
}
}
}
The idea is that I need to change the blue dot appearance but leave the functionalities as they need to be.
For some reason I can't find any course on advanced google maps customization. if you could refer a guy that does the thing, that would be awesome.

Drawing MKPolyline to be more accurate

So I am creating an app to track a user's running routes. I am to show a polyline that represents where a user has ran, between a start annotation that is dropped when user begins and a end annotation that is dropped when user clicks a finish button. Seeing as how someone can run pretty much anywhere, is there a way to draw a polyline that is Not limited to just main roads and streets? For example if someone runs somewhere that does not have main roads/streets, how would I show the polyline going through that area on the map? (See Image) Or is that not even possible in swift?
In addition, is it possible to fix these gaps?
Here is my code for rendering the polyline:
func drawPolyline() {
guard let startingCoordinate = self.startingCoordinate, let endingCoordinate = self.endingCoordinate else { return }
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: startingCoordinate))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: endingCoordinate))
request.transportType = .walking
let directions = MKDirections(request: request)
directions.calculate { [weak self] (response, error) in
guard let self = self else { return }
guard error == nil else { return }
guard response != nil else { return }
if let route = response?.routes.first {
self.mapView.addOverlay(route.polyline)
self.mapView.setVisibleMapRect(route.polyline.boundingMapRect, edgePadding: UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15), animated: true)
}
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay
renderer.strokeColor = .systemBlue
renderer.lineWidth = 3
return renderer
}
// code to get coordinate for annotations
guard let coordinate = locationManager.location?.coordinate else { return }
let annotation = MapAnnotation(title: title, coordinate: coordinate)
mapView.addAnnotation(annotation)
You will get an updated location every time it changes, and you can either build up an array of locations, or store them in a database for later retrieval.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
// the last location presented here is the current position of the runner
self.locations.append(locations.last)
// store this in a database, or as a class variable
}
You can set the desired accuracy when you initialise your location manager
locationManager.desiredAccuracy = kCLLocationAccuracyBest
and then when you're creating the map, create a line showing the runner's route
let polyline = MKPolyline(coordinates: self.locations, count: self.locations.count)
self.mapView.addOverlay(polyline)
Here's an example of the output - looks like the finish is in the middle of the run, but that's because I was heading back home

Swift 3 showing Firebase all users profile picture on map as annotation

I want to show user's profile pictures on map. I am storing datas on Firebase as longitude, latitude , photo as url on Firebase. Now, I am getting datas for all users on console. But I could not show these datas as annotation. Profile pictures will show on map according to longitude and latitude. How can I do this. I searched lots of websites and lots of tutorials. I could not find anything. All of shows that adding one picture on map as annotation. I want to do this for all users.`
class HomeTest: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
var ref = Database.database().reference()
var storageRef = Storage.storage().reference()
let manager = CLLocationManager()
var users = [User] ()
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
fetchUser()
}
func fetchUser() {
Database.database().reference().child("locations").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.latitude = dictionary["latitude"] as! Float
user.longitude = dictionary["longitude"] as! Float
user.photo = dictionary["photo"] as! String
//user.username = dictionary["username"] as! String
print(user.latitude, user.longitude, user.photo)
self.users.append(user)
DispatchQueue.main.async(execute: {
// ???
})
}
} , withCancel: nil)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations [0]
let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let span:MKCoordinateSpan = MKCoordinateSpanMake(0.020,0.020)
let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation,span)
self.mapView.setRegion(region, animated: true)
self.mapView.isZoomEnabled = true
self.mapView.isScrollEnabled = true
self.mapView.showsUserLocation = true
}
}

Route Between two A and B location

There is no error but I can not get the location from my current location to what I search. Can someone please help. It says this with I click on the Car logo to get directions: MKDirectionsErrorCode=7, NSLocalizedDescription=Directions Not Available}
I am only missing the line to get to the direction. When I click on the car logo, it just does not do anything but zoom out to my current location. I am missing anything or did something wrong?
Here is my code:
protocol HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark)
}
class ViewController: UIViewController {
#IBOutlet weak var mapView: MKMapView! // Handle the Map Kit View
var selectedPin:MKPlacemark? = nil //Any incoming placemarks
// Destination for directions*********
var destination:MKMapItem = MKMapItem()
var MyPosition = CLLocationCoordinate2D()
var resultSearchController:UISearchController? = nil // Keep the UISearchController in memory after it's created
var locationManager = CLLocationManager() // Core Location
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest // Accuracy level
locationManager.requestWhenInUseAuthorization() // Triggers the location permission dialog
locationManager.startUpdatingLocation()
//locationManager.requestLocation() // Trigers a one-time location request
// Set up the search results table
let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable") as! LocationSearchTable
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable
// Set up the search bar
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for places"
navigationItem.titleView = resultSearchController?.searchBar
// Configure the UISearchController appearance
resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
locationSearchTable.mapView = mapView // Passes along a handle of the mapView
locationSearchTable.handleMapSearchDelegate = self // Handles the map search
}
//Getting direction of location
#objc func getDirections(sender: AnyObject){
if let selectedPin = selectedPin {
let mapItem = MKMapItem(placemark: selectedPin)
//let launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving]
//mapItem.openInMaps(launchOptions: launchOptions)
let request = MKDirectionsRequest()
request.source = MKMapItem.forCurrentLocation()
request.destination = destination
request.requestsAlternateRoutes = false
let directions = MKDirections(request: request)
// 8.
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
let route = response.routes[0]
self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}
/*
directions.calculate(completionHandler: {(response: MKDirectionsResponse!, error: Error!) in
if error != nil {
print("Error \(error)")
} else {
self.displayRout(response)
var overlays = self.mapView.overlays
for route in response.routes {
self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)
for next in route.steps {
print(next.instructions)
}
}
}
})
}
*/
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 4.0
return renderer
}
}
//destination = MKMapItem(placemark: selectedPin!)
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : CLLocationManagerDelegate {
// When user responds to the permission dialog
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
// When location information comes back (Zoom to the user's current location)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
//****
MyPosition = location.coordinate
locationManager.stopUpdatingLocation()
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
// Print out the error
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error finding location: \(error.localizedDescription)")
}
}
// Searches the location and city/state
extension ViewController: HandleMapSearch {
func dropPinZoomIn(placemark:MKPlacemark){
// cache the pin
selectedPin = placemark
// clear existing pins
mapView.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = placemark.coordinate
annotation.title = placemark.name
if let city = placemark.locality,
let state = placemark.administrativeArea {
annotation.subtitle = "\(city) \(state)"
}
mapView.addAnnotation(annotation)
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegionMake(placemark.coordinate, span)
mapView.setRegion(region, animated: true)
}
}
// Shows Pins and Car Logo
extension ViewController : MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
if annotation is MKUserLocation {
//return nil so map view draws "blue dot" for standard user location
return nil
}
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView?.pinTintColor = UIColor.red
pinView?.canShowCallout = true
let smallSquare = CGSize(width: 30, height: 30)
let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSquare))
button.setBackgroundImage(UIImage(named: "Car"), for: .normal)
button.addTarget(self, action: #selector(getDirections), for: .touchUpInside)
pinView?.leftCalloutAccessoryView = button
return pinView
}
}
Have a look at below code for reference hope it helps :
1 using two locations here as source and as destination and drawing a path according to locations
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
// Do any additional setup after loading the view, typically from a nib.
let sourceLocation = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472)
let destinationLocation = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564)
// 3.
let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinationPlacemark = MKPlacemark(coordinate: destinationLocation, addressDictionary: nil)
// 4.
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinationMapItem = MKMapItem(placemark: destinationPlacemark)
// 5.
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = "Times Square"
if let location = sourcePlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
let destinationAnnotation = MKPointAnnotation()
destinationAnnotation.title = "Empire State Building"
if let location = destinationPlacemark.location {
destinationAnnotation.coordinate = location.coordinate
}
// 6.
self.mapView.showAnnotations([sourceAnnotation,destinationAnnotation], animated: true )
// 7.
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinationMapItem
directionRequest.transportType = .walking
// Calculate the direction
let directions = MKDirections(request: directionRequest)
// 8.
directions.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
let route = response.routes[0]
self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.blue
renderer.lineWidth = 4.0
return renderer
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Output :

Swift iOS google Map, path to coordinate

I am trying to create a function in my app that will guide the user to a marker I have created.
This is the code I am using, it works great, It gets the users current location and show it on the map. But how can I get a directions to a marker?
Any awnser will be helpful
class Karta: UIViewController, CLLocationManagerDelegate {
#IBOutlet var mapView: GMSMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//allow app to track user
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
//set out a marker on the map
var marker = GMSMarker()
marker.position = CLLocationCoordinate2DMake(56.675907, 12.858798)
marker.appearAnimation = kGMSMarkerAnimationPop
marker.icon = UIImage(named: "flag_icon")
marker.map = mapView
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Types Segue" {
let navigationController = segue.destinationViewController as UINavigationController
}
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
//If map is being used
if status == .AuthorizedWhenInUse {
var myLocation = mapView
locationManager.startUpdatingLocation()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
}
So i recently just solved this issue, here is my Swift 3 implementation using the latest version of Alamofire (4.3)
func fetchMapData() {
let directionURL = "https://maps.googleapis.com/maps/api/directions/json?" +
"origin=\(originAddressLat),\(originAddressLng)&destination=\(destinationAddressLat),\(destinationAddressLong)&" +
"key=YOUROWNSERVERKEY"
Alamofire.request(directionURL).responseJSON
{ response in
if let JSON = response.result.value {
let mapResponse: [String: AnyObject] = JSON as! [String : AnyObject]
let routesArray = (mapResponse["routes"] as? Array) ?? []
let routes = (routesArray.first as? Dictionary<String, AnyObject>) ?? [:]
let overviewPolyline = (routes["overview_polyline"] as? Dictionary<String,AnyObject>) ?? [:]
let polypoints = (overviewPolyline["points"] as? String) ?? ""
let line = polypoints
self.addPolyLine(encodedString: line)
}
}
}
func addPolyLine(encodedString: String) {
let path = GMSMutablePath(fromEncodedPath: encodedString)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 5
polyline.strokeColor = .blue
polyline.map = whateverYourMapViewObjectIsCalled
}
Disclaimer:Swift 2
func addOverlayToMapView(){
let directionURL = "https://maps.googleapis.com/maps/api/directions/json?origin=\(srcLocation.coordinate.latitude),\(srcLocation.coordinate.longitude)&destination=\(destLocation.coordinate.latitude),\(destLocation.coordinate.longitude)&key=Your Server Key"
Alamofire.request(.GET, directionURL, parameters: nil).responseJSON { response in
switch response.result {
case .Success(let data):
let json = JSON(data)
print(json)
let errornum = json["error"]
if (errornum == true){
}else{
let routes = json["routes"].array
if routes != nil{
let overViewPolyLine = routes![0]["overview_polyline"]["points"].string
print(overViewPolyLine)
if overViewPolyLine != nil{
self.addPolyLineWithEncodedStringInMap(overViewPolyLine!)
}
}
}
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}
Using the points, we now create the Path from two points using fromEncodedPath
func addPolyLineWithEncodedStringInMap(encodedString: String) {
let path = GMSMutablePath(fromEncodedPath: encodedString)
let polyLine = GMSPolyline(path: path)
polyLine.strokeWidth = 5
polyLine.strokeColor = UIColor.yellowColor()
polyLine.map = mapView
}
Unlike Apple's MapKit, the Google Maps SDK for iOS does not natively include a way to perform route calculations.
Instead, you need to use the Google Directions API: https://developers.google.com/maps/documentation/directions/. It is an HTTP-only API, and Google does not provide any SDK as of today, but you can easily write your own wrapper yourself, or choose one of the many options available on Github:
https://github.com/sudeepjaiswal/GoogleDirections
https://github.com/sebk/GoogleDirections
https://github.com/iamamused/iOS-DirectionKit
https://github.com/marciniwanicki/OCGoogleDirectionsAPI
and many others...
Its Very Simple
if you added a Google map SDK in your iOS Project and if you want to implement get google map direction lines between two different directions i have made as demo code in simple way understand using swift 2.3 try it, modify it and use it.!!!
Note: Dont Forgot to change your lat long you want and API Key (You may Use API key with None Restrictions on Google API Manager Credential Section)
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(CGRect.zero, 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
view = mapView
}