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,
These lines shows location between a given latitude / longitude and user location;
NSString *googleMapUrlString = [NSString stringWithFormat:@"http://maps.google.com/?saddr=%f,%f&daddr=%@,%@", mapView.userLocation.coordinate.latitude, mapView.userLocation.coordinate.longitude, destinationLatitude, destinationLongtitude];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleMapUrlString]];
(void)viewDidLoad {
[super viewDidLoad];
GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:30.692408
longitude:76.767556
zoom:14];
GMSMapView *mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
mapView.myLocationEnabled = YES;
// Creates markers in the center of the map.
GMSMarker *marker = [[GMSMarker alloc] init];
marker.position = CLLocationCoordinate2DMake(30.6936659, 76.77201819999999);
marker.title = @"Chandigarh 47c";
marker.snippet = @"Hello World";
marker.map = mapView;
GMSMarker *marker1 = [[GMSMarker alloc] init];
marker1.position = CLLocationCoordinate2DMake(30.742138, 76.818756);
marker1.title = @"Sukhna Lake";
marker1.map = mapView;
//creating a path
GMSMutablePath *path = [GMSMutablePath path];
[path addCoordinate:CLLocationCoordinate2DMake(@(30.6936659).doubleValue,@(76.77201819999999).doubleValue)];
[path addCoordinate:CLLocationCoordinate2DMake(@(30.742138).doubleValue,@(76.818756).doubleValue)];
GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
rectangle.strokeWidth = 2.f;
rectangle.map = mapView;
self.view=mapView;
}
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"]
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.
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.
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()
}