web-dev-qa-db-fra.com

Google Maps iOS SDK, Obtenir les itinéraires entre 2 lieux

Pendant que j'utilise Google Maps SDK, j'essaie d'obtenir le sens de la conduite entre deux emplacements sur iOS. Je sais que nous pouvons le faire en utilisant deux méthodes: -

1.) Utilisation du schéma d'URL pour lequel il est nécessaire que Google Maps App soit installé sur votre appareil.

2.) À l'aide de l'API Directions, via Request-Response, puis en analysant le JSON. Afficher des marqueurs pour montrer la direction.

Maintenant, ma question est-il un autre moyen par lequel je peux le faire sur iOS? J'ai besoin d'indiquer la direction de mon emplacement actuel à un emplacement particulier dont je dispose le Lat/Long.

Je veux dire est-il vraiment pas possible de simplement passer 2 emplacement comme paramètre et Google Maps SDK, va me donner les instructions?

Merci,

26
Amit Singh

On dirait que vous recherchez une interface utilisateur Chrome, comme l’application Google Maps l’affiche. Google Maps SDK pour iOS vous peindra une carte, mais vous êtes responsable du chrome supplémentaire de navigation.

Vous pouvez utiliser le Google Directions API pour demander des directions, puis utiliser le chemin codé renvoyé par le service pour dessiner une méthode GMSPolyline en utilisant le chemin pathFromEncodedPath de GMSPath: .

19
Brett
    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]);

Remarque: assurez-vous que le lecteur de DVD de votre API Google Direction est activé dans votre console de développeur Google.

42
Muhammad Noman

Ces lignes indiquent l’emplacement entre une latitude/longitude donnée et l’emplacement de l’utilisateur;

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]];
12
Engnyl

Swift 3.0 & XCode 8.0 Utilisation d’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)

        })
8
Sourabh Sharma

Je l'avais fait car il montre également PINS DISTANCE ET DURÉE sur la carte avec DIRECTION ROUTE . Mais n'oubliez pas de configurer votre API GOOGLE DIRECTION SUR ACTIVÉ dans votre CONSOLE GOOGLE DEVELOPER

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

NSString *urlString =@"https://maps.googleapis.com/maps/api/directions/json";

 NSDictionary *dictParameters = @{@"Origin" : [NSString stringWithFormat:@"%@",_sourceAdd], @"destination" : [NSString stringWithFormat:@"%@",_destinationAdd], @"mode" : @"driving", @"key":@"AIzaSyD9cWTQkAxemELVXTNUCALOmzlDv5b9Dhg"};

[manager GET:urlString parameters:dictParameters success:^(AFHTTPRequestOperation *operation, id responseObject) {


    GMSPath *path =[GMSPath pathFromEncodedPath:responseObject[@"routes"][0][@"overview_polyline"][@"points"]];
    NSDictionary *arr=responseObject[@"routes"][0][@"legs"];
    NSMutableArray *loc=[[NSMutableArray alloc]init];

    loc=[[arr valueForKey:@"start_location"]valueForKey:@"lat"];
    _sourceloc.latitude=[loc[0] doubleValue];

    loc=[[arr valueForKey:@"start_location"]valueForKey:@"lng"];
    _sourceloc.longitude=[loc[0] doubleValue];

    loc=[[arr valueForKey:@"end_location"]valueForKey:@"lat"];
    _destinationloc.latitude=[loc[0] doubleValue];

    loc=[[arr valueForKey:@"end_location"]valueForKey:@"lng"];
    _destinationloc.longitude=[loc[0] doubleValue];


    NSString *dis,*dur;
    loc=[[arr valueForKey:@"distance"]valueForKey:@"text"];
    dis=loc[0];

    loc=[[arr valueForKey:@"duration"]valueForKey:@"text"];
    dur=loc[0];


    NSString *sa,*da;
    loc=[arr valueForKey:@"start_address"];
    sa=loc[0];

    loc=[arr valueForKey:@"end_address"];
    da=loc[0];

    UIAlertView *av=[[UIAlertView alloc]initWithTitle:@"Route Info" message:[NSString stringWithFormat:@"Distance:%@ \nDuration:%@",dis,dur] delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
    [av show];



    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:_sourceloc.latitude  longitude:_sourceloc.longitude zoom:10];
    mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];

    GMSMarker *marker = [GMSMarker markerWithPosition:_sourceloc];
    marker.title=@"Source";
    marker.snippet =sa;
    marker.appearAnimation = kGMSMarkerAnimationPop;
    marker.map = mapView;


    GMSMarker *marker2 = [GMSMarker markerWithPosition:_destinationloc];
    marker2.title=@"Destination";
    marker2.snippet =da;
    marker2.appearAnimation = kGMSMarkerAnimationPop;
    marker2.map = mapView;

    GMSPolyline *singleLine = [GMSPolyline polylineWithPath:path];
    singleLine.strokeWidth = 4;
    singleLine.strokeColor = [UIColor blueColor];
    singleLine.map = mapView;

    self.view = mapView;



} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];
8
Patel Jigar

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()

Ici, vous devez ajouter votre clé (clé Google Api) à l'API ci-dessus.

2
iOS
(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;

 }
1
Navneet Singh Rana

Créez une clé dans la console de développement Google pour vous assurer que votre projet est créé avec App bundleID après avoir ajouté le code suivant 

NSString *KEY=@"";
NSString *Origin=@"";
NSString *Destination=@"";
NSString *str_maps=[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&key=%@",Origin,Destination,KEY];
NSURL *url=[NSURL URLWithString:str_maps];
 NSData *dta=[NSData dataWithContentsOfURL:url];
NSDictionary *dict=(NSDictionary *)[NSJSONSerialization JSONObjectWithData:dta options:kNilOptions error:nil];
NSLog(@"%@",dict);
0
Manoj Reddy