Swift iOS google Map, path to coordinate
Asked Answered
R

4

5

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()
        }
    }
}
Relevance answered 28/2, 2015 at 16:30 Comment(0)
V
5

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:

Vasti answered 28/2, 2015 at 16:44 Comment(2)
Thanks man for your help, I'll look into this! Would you prefer to use the iOS map instead if I want to use this function?Relevance
I've been using both, and from my own experience, Google Maps usually gives better results, at least in Europe. However, MapKit is easier to use, as it is tightly integrated to the iOS SDK, and immediately available for use.Vasti
E
18

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

}
Edington answered 1/2, 2017 at 23:40 Comment(1)
"&" is missing in URL before originClodhopper
S
8

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

    }
Savior answered 23/12, 2015 at 12:9 Comment(7)
Sorry but what is the JSON in let json = JSON(data) ?Chaos
it just contains the key value pair ..info about the route in different keys..however our main concern is with polyline points....Spaulding
It 's work for me after about 1 day coding. That 's my bad skill. Thanks for your code :)Chaos
@Anish웃.. This helped me. One doubt i get latitude & longitude from server how to position of marker in swiftAbandoned
@Anish웃.. I have done on doing some research.But in tracking the user it is not setting proper.Abandoned
Please ask a different question.For tracking you need to use location Manager and get user location and plot in map clearing the previous location marker..Or use the default showUserLocation that will auto update in map according to user location without LocationManagerSpaulding
I would not recommend storing a ServerKey in a Client Application (like an iOS application). It can lead to security issue, if your application get decompiled, etc.Fructose
V
5

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:

Vasti answered 28/2, 2015 at 16:44 Comment(2)
Thanks man for your help, I'll look into this! Would you prefer to use the iOS map instead if I want to use this function?Relevance
I've been using both, and from my own experience, Google Maps usually gives better results, at least in Europe. However, MapKit is easier to use, as it is tightly integrated to the iOS SDK, and immediately available for use.Vasti
D
2

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

    }
Dripping answered 29/9, 2016 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.