Trazado de Ruta Entre Dos Lugares en GMSMapView en iOS


Estoy Desarrollando una aplicación iOS. En esa Aplicación estoy teniendo 2 Campos Desde y Hacia. Ingresé la dirección usando la API de Google Auto Complete.y también soy capaz de Llegar el Latitud y Longitud de los 2 lugares y capaz de mostrar los marcadores en el GMSMapView.

Ahora Quiero Dibujar Una Ruta Entre estos 2 Lugares. Encontré una solución cuando usamos MKMapView. Pero no pude encontrar la solución para GMSMapView. por favor, ayúdame a dibujar la ruta entre estos 2 puntos en GMSMapView.

Si es posible, por favor dame algunos enlaces importantes para esto.

Gracias.

Author: S R Nayak, 2014-03-21

10 answers

`first get all points coordinates which are coming in route then add these points latitude and longitude in path in will draw path according to that`


GMSCameraPosition *cameraPosition=[GMSCameraPosition cameraWithLatitude:18.5203 longitude:73.8567 zoom:12];
_mapView =[GMSMapView mapWithFrame:CGRectZero camera:cameraPosition];
_mapView.myLocationEnabled=YES;
GMSMarker *marker=[[GMSMarker alloc]init];
marker.position=CLLocationCoordinate2DMake(18.5203, 73.8567);
marker.icon=[UIImage imageNamed:@"aaa.png"] ;
marker.groundAnchor=CGPointMake(0.5,0.5);
marker.map=_mapView;
GMSMutablePath *path = [GMSMutablePath path];   
[path addCoordinate:CLLocationCoordinate2DMake(@(18.520).doubleValue,@(73.856).doubleValue)];
[path addCoordinate:CLLocationCoordinate2DMake(@(16.7).doubleValue,@(73.8567).doubleValue)];

GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
rectangle.strokeWidth = 2.f;
rectangle.map = _mapView;
self.view=_mapView;
 31
Author: johny kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-21 05:40:27

He escrito el siguiente código que debería hacer el truco para usted:

- (void)drawRoute
{
    [self fetchPolylineWithOrigin:myOrigin destination:myDestination completionHandler:^(GMSPolyline *polyline)
     {
         if(polyline)
             polyline.map = self.myMap;
     }];
}

- (void)fetchPolylineWithOrigin:(CLLocation *)origin destination:(CLLocation *)destination completionHandler:(void (^)(GMSPolyline *))completionHandler
{
    NSString *originString = [NSString stringWithFormat:@"%f,%f", origin.coordinate.latitude, origin.coordinate.longitude];
    NSString *destinationString = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];
    NSString *directionsAPI = @"https://maps.googleapis.com/maps/api/directions/json?";
    NSString *directionsUrlString = [NSString stringWithFormat:@"%@&origin=%@&destination=%@&mode=driving", directionsAPI, originString, destinationString];
    NSURL *directionsUrl = [NSURL URLWithString:directionsUrlString];


    NSURLSessionDataTask *fetchDirectionsTask = [[NSURLSession sharedSession] dataTaskWithURL:directionsUrl completionHandler:
         ^(NSData *data, NSURLResponse *response, NSError *error)
         {
             NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
             if(error)
             {
                 if(completionHandler)
                     completionHandler(nil);
                 return;
             }

             NSArray *routesArray = [json objectForKey:@"routes"];

             GMSPolyline *polyline = nil;
             if ([routesArray count] > 0)
             {
                 NSDictionary *routeDict = [routesArray objectAtIndex:0];
                 NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
                 NSString *points = [routeOverviewPolyline objectForKey:@"points"];
                 GMSPath *path = [GMSPath pathFromEncodedPath:points];
                 polyline = [GMSPolyline polylineWithPath:path];
             }

             // run completionHandler on main thread                                           
             dispatch_sync(dispatch_get_main_queue(), ^{
                 if(completionHandler)
                      completionHandler(polyline);
             });
         }];
    [fetchDirectionsTask resume];
}
 28
Author: Tarek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-02 00:03:23

Para swift 3 dibujar polilínea

func getPolylineRoute(from source: CLLocationCoordinate2D, to destination: CLLocationCoordinate2D){

        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(source.latitude),\(source.longitude)&destination=\(destination.latitude),\(destination.longitude)&sensor=true&mode=driving&key=YOURKEY")!

        let task = session.dataTask(with: url, completionHandler: {
            (data, response, error) in
            if error != nil {
                print(error!.localizedDescription)
                self.activityIndicator.stopAnimating()
            }
            else {
                do {
                    if let json : [String:Any] = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{

                        guard let routes = json["routes"] as? NSArray else {
                            DispatchQueue.main.async {
                                self.activityIndicator.stopAnimating()
                            }
                            return
                        }

                        if (routes.count > 0) {
                            let overview_polyline = routes[0] as? NSDictionary
                            let dictPolyline = overview_polyline?["overview_polyline"] as? NSDictionary

                            let points = dictPolyline?.object(forKey: "points") as? String

                            self.showPath(polyStr: points!)

                            DispatchQueue.main.async {
                                self.activityIndicator.stopAnimating()

                                let bounds = GMSCoordinateBounds(coordinate: source, coordinate: destination)
                                let update = GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(170, 30, 30, 30))
                                self.mapView!.moveCamera(update)
                            }
                        }
                        else {
                            DispatchQueue.main.async {
                                self.activityIndicator.stopAnimating()
                            }
                        }
                    }
                }
                catch {
                    print("error in JSONSerialization")
                    DispatchQueue.main.async {
                        self.activityIndicator.stopAnimating()
                    }
                }
            }
        })
        task.resume()
    }

    func showPath(polyStr :String){
        let path = GMSPath(fromEncodedPath: polyStr)
        let polyline = GMSPolyline(path: path)
        polyline.strokeWidth = 3.0
        polyline.strokeColor = UIColor.red
        polyline.map = mapView // Your map view
    }

Nota: Debe poner la clave de la API de googleDirection en la URL.

 10
Author: Hardik Thakkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-19 12:42:56

Si alguien está buscando un Swift 3.0 para la respuesta de @Tarek, puede usar esto. Esto también usa Alamofire y SwiftyJSON .

func drawPath()
{
    let origin = "\(currentLocation.latitude),\(currentLocation.longitude)"
    let destination = "\(destinationLoc.latitude),\(destinationLoc.longitude)"


    let url = "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=driving&key=YOURKEY"

    Alamofire.request(url).responseJSON { response in
      print(response.request)  // original URL request
      print(response.response) // HTTP URL response
      print(response.data)     // server data
      print(response.result)   // result of response serialization

      let json = JSON(data: response.data!)
      let routes = json["routes"].arrayValue

      for route in routes
      {
        let routeOverviewPolyline = route["overview_polyline"].dictionary
        let points = routeOverviewPolyline?["points"]?.stringValue
        let path = GMSPath.init(fromEncodedPath: points!)
        let polyline = GMSPolyline.init(path: path)
        polyline.map = self.mapView
      }
    }
  }
 8
Author: Christian Abella,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-15 06:46:59

Aquí hay una rápida traducción de la respuesta de johny kumar.

let cameraPositionCoordinates = CLLocationCoordinate2D(latitude: 18.5203, longitude: 73.8567)
    let cameraPosition = GMSCameraPosition.cameraWithTarget(cameraPositionCoordinates, zoom: 12)

    let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: cameraPosition)
    mapView.myLocationEnabled = true

    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2DMake(18.5203, 73.8567)
    marker.groundAnchor = CGPointMake(0.5, 0.5)
    marker.map = mapView

    let path = GMSMutablePath()
    path.addCoordinate(CLLocationCoordinate2DMake(18.520, 73.856))
    path.addCoordinate(CLLocationCoordinate2DMake(16.7, 73.8567))

    let rectangle = GMSPolyline(path: path)
    rectangle.strokeWidth = 2.0
    rectangle.map = mapView

    self.view = mapView
 4
Author: Pomme2Poule,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-07 14:49:21

Realice una solicitud de URL a la API de Google Directions y cuando reciba un archivo JSON, siga todos los pasos y decodifique los objetos points.

 2
Author: WWJD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-21 16:20:47

- Swift 3.0 & XCode 8.0 Línea Staright: (

let cameraPosition = GMSCameraPosition.camera(withLatitude: 18.5203, longitude: 73.8567, zoom: 12)
        self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: cameraPosition)
        self.mapView.isMyLocationEnabled = true
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2DMake(18.5203, 73.8567)
       // marker.icon = UIImage(named: "aaa.png")!
        marker.groundAnchor = CGPoint(x: 0.5, y: 0.5)
        marker.map = mapView
        let path = GMSMutablePath()
        path.add(CLLocationCoordinate2DMake(CDouble((18.520)), CDouble((73.856))))
        path.add(CLLocationCoordinate2DMake(CDouble((16.7)), CDouble((73.8567))))
        let rectangle = GMSPolyline.init(path: path)
        rectangle.strokeWidth = 2.0
        rectangle.map = mapView
        self.view = mapView
 2
Author: Sourabh Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-27 14:36:36

Lo he hecho con AlamoFire y SwiftyJSON en xCode 8.3.3 y Swift 3.1. Coloque el dibujo de la ruta en una función que solo necesita dos parámetros

Un ejemplo de origen de cadena " 48.7788, 9.22222" y un ejemplo de destino de cadena "49.3212232, 8.334151"

func drawPath (origin: String, destination: String) {
    /* set the parameters needed */ 
    String prefTravel = "walking" /* options are driving, walking, bicycling */
    String gmapKey = "Ask Google"
    /* Make the url */
    let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)&mode=\(prefTravel)&key=" + gmapKey)

    /* Fire the request */
    Alamofire.request(url!).responseJSON{(responseData) -> Void in
        if((responseData.result.value) != nil) {
            /* read the result value */
            let swiftyJsonVar = JSON(responseData.result.value!)
            /* only get the routes object */
            if let resData = swiftyJsonVar["routes"].arrayObject {
                let routes = resData as! [[String: AnyObject]]
                /* loop the routes */
                if routes.count > 0 {
                    for rts in routes {
                       /* get the point */
                       let overViewPolyLine = rts["overview_polyline"]?["points"]
                       let path = GMSMutablePath(fromEncodedPath: overViewPolyLine as! String)
                       /* set up poly line */
                       let polyline = GMSPolyline.init(path: path)
                       polyline.strokeWidth = 2
                       polyline.map = self.mapView
                    }
                }
            }
        }
    }
}
 2
Author: Charley57,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-14 10:20:03

Hola Puede usar "LRouteController", es una mejor manera de mostrar la ruta de carretera entre dos puntos como:

[_routeController getPolyline With Locations: (Array of first and last location)]

Pruébelo, espero que resuelva su problema.

 0
Author: Parkhya developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-02 06:23:16

DirectionResponse desde la APIGoogle Directions Los NSLogs son útiles para ver con qué está trabajando.

[[GMDirectionService sharedInstance] getDirectionsFrom:origin to:destination          succeeded:^(GMDirection *directionResponse) {   
if ([directionResponse statusOK]){
    NSLog(@"Duration : %@", [directionResponse durationHumanized]);
    NSLog(@"Distance : %@", [directionResponse distanceHumanized]);
    NSArray *routes = [[directionResponse directionResponse] objectForKey:@"routes"];
    // NSLog(@"Route : %@", [[directionResponse directionResponse] objectForKey:@"routes"]);

    GMSPath *path = [GMSPath pathFromEncodedPath:routes[0][@"overview_polyline"]  [@"points"]];
    GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
    polyline.strokeColor = [UIColor redColor];
    polyline.strokeWidth = 5.f;
    polyline.map = mapView;

}
} failed:^(NSError *error) {
    NSLog(@"Can't reach the server")
}];
 0
Author: Nil Rathod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-15 11:36:36