JUST IN TWO STEP:
Step 1: Call google map plote route API.
Step 2: Handle the response for route, distance and duration.
*****STEP 1:*****
/* request google direction GET APIs */
func requestGoogleMapsDirectionApis(originLat: String,originLong:String, destinationLat:String, destinationLong:String, onSuccess:@escaping (_ response:AnyObject)->Void, onError:@escaping (_ errorMessage:String)->Void)->Void{
// GOOGLE DIRECTION APIS DEMO
// https://maps.googleapis.com/maps/api/directions/json?origin=27.696981,85.2942719&destination=27.6792144,85.3632975&sensor=false&mode=driving&alternatives=falseGOOGLE_MAP_API_KEY
let url:String = "https://maps.googleapis.com/maps/api/directions/json?origin=\(originLat),\(originLong)&destination=\(destinationLat),\(destinationLong)&sensor=false&mode=driving&alternatives=false\(MAP_API_KEY)"
showLog(classname: classname, tagName: "**FULL URL \(url)")
Alamofire.request(url, method: .get).responseJSON { response in
showLog(classname: classname , tagName: "\n*** RESPONSE SERIALIZATION:\n \(response.result)") // result of response serialization
switch response.result {
case .success:
if let jsonObject = response.result.value{
showLog(classname: classname, tagName: "\n*** OnSuccessResponse: \(jsonObject as AnyObject)")
onSuccess(jsonObject as AnyObject)
}
case .failure:
/* Handle error just using simple message */
showLog(classname: classname, tagName: "\n*** OnErrorResponse: \(response)")
onError("failure")
}
}
*****STEP 2:*****
/*
* PLOT ROUTE IN GOOGLE MAP
* CALCULATE DISTANCE
* CALCULATE TIME
*/
func callPlotRouteCalcDistanceAndTimeApis(originLat:String, originLong:String, destinationLat:String, destinationLong:String){
homeViewCOntroller.view.makeToastActivity(.center)
requestGoogleMapsDirectionApis(originLat: originLat, originLong: originLong, destinationLat: destinationLat, destinationLong: destinationLong, onSuccess: { (response) in
// filter data
// set data to model
// plot route in google map
showLog(classname: self.className, tagName: response)
self.responseJsonObjectFilter(jsonObject: response)
self.homeViewCOntroller.view.hideToastActivity()
}) { (failureMsz) in
showLog(classname: self.className, tagName: failureMsz)
self.homeViewCOntroller.view.hideToastActivity()
}
}
/* Response object filter PLOT ROUTE APIs for SUCCESS or FAILED */
func responseJsonObjectFilter(jsonObject:AnyObject){
showLog(classname: className ,tagName: "responseJsonObjectFilter")
if let jsonObjectDictionary = jsonObject as? NSDictionary {
if let statusMessage = jsonObjectDictionary["status"] as? String{
if(statusMessage == "OK"){
if let routesObject = jsonObjectDictionary["routes"] as? [Any] {
if routesObject[0] is NSDictionary {
let anyObject:AnyObject = routesObject[0] as AnyObject
if let routeObjectDictionary = anyObject as? NSDictionary{
/* legs KEY for duration and distance */
if let legsObject = routeObjectDictionary["legs"] as? [Any] {
let legsAnyObject:AnyObject = legsObject[0] as AnyObject
if let legsObjectDictionary = legsAnyObject as? NSDictionary{
showLog(classname: className, tagName: legsObjectDictionary)
/* DISTANCE KEY for distance */
if let distanceObjectNsDictionary = legsObjectDictionary["distance"] as? NSDictionary {
var estimatedDistance:Double = distanceObjectNsDictionary["value"] as! Double
estimatedDistance = estimatedDistance/1000
bookingModel.estimatedDistance = String(format: "%.2f", estimatedDistance)
}
/* DURATION KEY for duration */
if let durationObjectNsDictionary = legsObjectDictionary["duration"] as? NSDictionary {
var estimatedTime:Double = durationObjectNsDictionary["value"] as! Double
estimatedTime = estimatedTime/60
bookingModel.estimatedTime = "\(estimatedTime)"
}
}
}
/* overview_polyline KEY for duration and distance */
if let poylineObjectNsDictionary = routeObjectDictionary["overview_polyline"] as? NSDictionary {
showLog(classname: className, tagName: poylineObjectNsDictionary["points"] as! String)
bookingModel.route = poylineObjectNsDictionary["points"] as? String
generateRoute(uiMapView:homeViewCOntroller.uiMapView, encodedString: poylineObjectNsDictionary["points"] as! String)
}
}
}
}
}else{
showSnackbar(uiView: self.homeViewCOntroller.view, message: "Could not plot route. Please check your internet connection.")
}
}
}
self.homeViewCOntroller.view.hideToastActivity()
}
/* Generate ROUTE to UIMapView */
func generateRoute(uiMapView:GMSMapView, encodedString:String){
uiMapView.clear()
let path = GMSMutablePath(fromEncodedPath: encodedString)
let polyLine = GMSPolyline(path: path)
polyLine.strokeWidth = 3
polyLine.strokeColor = hexStringToUIColor(hex: redColor)
polyLine.map = uiMapView
let polyline = Polyline(encodedPolyline: encodedString)
let decodedCoordinates: [CLLocationCoordinate2D]? = polyline.coordinates
let pickupLat = decodedCoordinates?[0].latitude
let pickupLong = decodedCoordinates?[0].longitude
let dropLat = decodedCoordinates?[((decodedCoordinates?.count)! - 1)].latitude
let dropLong = decodedCoordinates?[((decodedCoordinates?.count)! - 1)].longitude
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: pickupLat!, longitude: pickupLong!)
marker.snippet = "Pickup Location"
marker.icon = UIImage(named: "ic_pin_pick.png")
marker.map = uiMapView
// Creates a marker in the center of the map.
let marker2 = GMSMarker()
marker2.position = CLLocationCoordinate2D(latitude: dropLat!, longitude: dropLong!)
marker2.snippet = "Drop Location"
marker2.icon = UIImage(named: "ic_pin_drop.png")
marker2.map = uiMapView
}