Google Maps iOS SDK, Getting Directions between 2

2020-01-29 03:54发布

While I am using Google Maps SDK, I am trying to get driving direction between two locations on iOS. I know we can do this using two methods:-

1.) Using URL Scheme, for which it is necessary that Google Maps App is installed on your device.

2.) Using Directions API, via Request-Response and then parsing the JSON. Displaying markers to show the direction.

Now, my question is there any other way by which I can do this on iOS? I need to show the direction from my current location to a particular location of which i have the Lat/Long.

I mean is it really not possible to simply pass 2 location as parameter and Google Maps SDK, will give me the directions?

Thanks,

10条回答
淡お忘
2楼-- · 2020-01-29 03:55
    NSString *urlString = [NSString stringWithFormat:
                       @"%@?origin=%f,%f&destination=%f,%f&sensor=true&key=%@",
                       @"https://maps.googleapis.com/maps/api/directions/json",
                       mapView.myLocation.coordinate.latitude,
                       mapView.myLocation.coordinate.longitude,
                       destLatitude,
                       destLongitude,
                       @"Your Google Api Key String"];
NSURL *directionsURL = [NSURL URLWithString:urlString];


ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:directionsURL];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
    NSString *response = [request responseString];
    NSLog(@"%@",response);
    NSDictionary *json =[NSJSONSerialization JSONObjectWithData:[request responseData] options:NSJSONReadingMutableContainers error:&error];
    GMSPath *path =[GMSPath pathFromEncodedPath:json[@"routes"][0][@"overview_polyline"][@"points"]];
    GMSPolyline *singleLine = [GMSPolyline polylineWithPath:path];
    singleLine.strokeWidth = 7;
    singleLine.strokeColor = [UIColor greenColor];
    singleLine.map = self.mapView;
}
else NSLog(@"%@",[request error]);

Note: make Sure Your Google Direction API Sdk Is Enable in Your google developer Console.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-01-29 04:01

Swift 4.1, Xcode 9.4.1

//Here you need to set your origin and destination points and mode 
let url = NSURL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=Machilipatnam&destination=Vijayawada&mode=driving")

//OR if you want to use latitude and longitude for source and destination
//let url = NSURL(string: "\("https://maps.googleapis.com/maps/api/directions/json")?origin=\("17.521100"),\("78.452854")&destination=\("15.1393932"),\("76.9214428")")

        let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) -> Void in

            do {
                if data != nil {
                    let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as!  [String:AnyObject]
//                        print(dic)

                    let status = dic["status"] as! String
                    var routesArray:String!
                    if status == "OK" {
                        routesArray = (((dic["routes"]!as! [Any])[0] as! [String:Any])["overview_polyline"] as! [String:Any])["points"] as! String
//                            print("routesArray: \(String(describing: routesArray))")
                    }

                    DispatchQueue.main.async {
                        let path = GMSPath.init(fromEncodedPath: routesArray!)
                        let singleLine = GMSPolyline.init(path: path)
                        singleLine.strokeWidth = 6.0
                        singleLine.strokeColor = .blue
                        singleLine.map = mapView
                    }

                }
            } catch {
                print("Error")
            }
        }

        task.resume()

Here, you need to add your key (google api key) to the above API.

查看更多
家丑人穷心不美
4楼-- · 2020-01-29 04:03

If someone is looking to parse the distance from routes array following is the way to get the distance in swift 4/5

let distance = responseJSON["routes"][0]["legs"][0]["distance"]["text"]
查看更多
萌系小妹纸
5楼-- · 2020-01-29 04:05

It sounds like you are looking for UI Chrome like the Google Maps app has for showing directions. Google Maps SDK for iOS will paint you a map, but you are responsible for the additional navigation chrome.

You can use the Google Directions API to request directions, and then use the encoded path returned from the service to draw a GMSPolyline using GMSPath's pathFromEncodedPath: method.

查看更多
再贱就再见
6楼-- · 2020-01-29 04:07

Swift 3.0 & XCode 8.0 Using AFNetworking & SwiftJson

        let destLatitude="26.9124"
        let destLongitude="75.7873"
        mapView.isMyLocationEnabled = true
        var urlString = "\("https://maps.googleapis.com/maps/api/directions/json")?origin=\("28.7041"),\("77.1025")&destination=\(destLatitude),\(destLongitude)&sensor=true&key=\("Your-Api-key")"

        urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!

        let manager=AFHTTPRequestOperationManager()

        manager.responseSerializer = AFJSONResponseSerializer(readingOptions: JSONSerialization.ReadingOptions.allowFragments) as AFJSONResponseSerializer

        manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer

        manager.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/html", "text/plain", "text/json", "text/javascript", "audio/wav") as Set<NSObject>


        manager.post(urlString, parameters: nil, constructingBodyWith: { (formdata:AFMultipartFormData!) -> Void in

            }, success: {  operation, response -> Void in
                //{"responseString" : "Success","result" : {"userId" : "4"},"errorCode" : 1}
                //if(response != nil){
                let parsedData = JSON(response)
                print_debug("parsedData : \(parsedData)")
               var path = GMSPath.init(fromEncodedPath: parsedData["routes"][0]["overview_polyline"]["points"].string!)
                 //GMSPath.fromEncodedPath(parsedData["routes"][0]["overview_polyline"]["points"].string!)
                var singleLine = GMSPolyline.init(path: path)
                singleLine.strokeWidth = 7
                singleLine.strokeColor = UIColor.green
                singleLine.map = self.mapView
                //let loginResponeObj=LoginRespone.init(fromJson: parsedData)


                //  }
            }, failure: {  operation, error -> Void in

                print_debug(error)
                let errorDict = NSMutableDictionary()
                errorDict.setObject(ErrorCodes.errorCodeFailed.rawValue, forKey: ServiceKeys.keyErrorCode.rawValue as NSCopying)
                errorDict.setObject(ErrorMessages.errorTryAgain.rawValue, forKey: ServiceKeys.keyErrorMessage.rawValue as NSCopying)

        })
查看更多
时光不老,我们不散
7楼-- · 2020-01-29 04:13

Using Swift I definitely solved in this way.
My purpose was finding distance between two coordinates:

import AFNetworking 

/**
 Calculate distance between two valid coordinates

 - parameter origin:      origin coordinates
 - parameter destination: destination coordinates
 - parameter completion:  completion callback
 */
func calculateDistance(origin origin: CLLocation, destination: CLLocation, completion: (distance: Double?) -> Void) {

    let service = "https://maps.googleapis.com/maps/api/directions/json"
    let originLat = origin.coordinate.latitude
    let originLong = origin.coordinate.longitude
    let destLat = destination.coordinate.latitude
    let destLong = destination.coordinate.longitude
    let urlString = "\(service)?origin=\(originLat),\(originLong)&destination=\(destLat),\(destLong)&mode=driving&units=metric&sensor=true&key=<YOUR_KEY>"
    let directionsURL = NSURL(string: urlString)

    let request = NSMutableURLRequest(URL: directionsURL!)

    request.HTTPMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    let operation = AFHTTPRequestOperation(request: request)
    operation.responseSerializer = AFJSONResponseSerializer()

    operation.setCompletionBlockWithSuccess({ (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in

        if let result = responseObject as? NSDictionary {
            if let routes = result["routes"] as? [NSDictionary] {
                if let lines = routes[0]["overview_polyline"] as? NSDictionary {
                    if let points = lines["points"] as? String {
                        let path = GMSPath(fromEncodedPath: points)
                        let distance = GMSGeometryLength(path)
                        print("wow \(distance / 1000) KM")

                    }
                }
            }
        }
        }) { (operation: AFHTTPRequestOperation!, error: NSError!)  -> Void in
            print("\(error)")
    }

    operation.start()

}
查看更多
登录 后发表回答