Drawing Route Between Two Places on GMSMapView in

2019-01-03 08:53发布

I am Developing an iOS Application. In that Application i am having 2 Fields From and To. I Entered Address using Google Auto Complete API.and also i am able to Getting the Latitude and Longitude of the 2 places and able to show markers on the GMSMapView.

Now i Want to Draw Route Between these 2 Places. I found a solution when we use MKMapView. But i was Unable to find the solution for GMSMapView. please help me to Draw the route between these 2 points in GMSMapView.

If possible please give me some important links for this.

Thanks.

10条回答
干净又极端
2楼-- · 2019-01-03 09:21

I have made it with AlamoFire and SwiftyJson in xCode 8.3.3 and Swift 3.1. Put the drawing of the path in a function that needs two parameters only

a String origin example "48.7788,9.22222" and a String destination example "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
                    }
                }
            }
        }
    }
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-01-03 09:22

Make an URL request to Google Directions API and when you receive a JSON file go through all steps and decode the points objects.

查看更多
淡お忘
4楼-- · 2019-01-03 09:23

Hi You can use "LRouteController", it is a best way to show road route between two points like :

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

Try it, I hope it will resolve your problem.

查看更多
\"骚年 ilove
5楼-- · 2019-01-03 09:24

DirectionResponse from the Google Directions APIThe NSLogs are useful to see what you are working with.

[[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")
}];
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-03 09:27
`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;
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-03 09:27

I've written the following code which should do the trick for you:

- (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];
}
查看更多
登录 后发表回答