user 12345
user 12345

Reputation: 23

How to draw GMSPolyline in MapView

I have create a map based app. Now Fetched PolyLine points by google direction api. But how to draw poly line with this GSMPath. I tried to many times but not draw polyLine in GMSMapView. How to draw please suggest. Which methods are use please guide.

-(void) viewWillAppear:(BOOL)animated
{
NSString *urlString = [NSString stringWithFormat:
                       @"%@?origin=%f,%f&destination=%f,%f&sensor=true&key=%@",
                       @"https://maps.googleapis.com/maps/api/directions/json",
                       22.6987,
                       75.8817,
                       22.6990,
                       75.8671,
                       @"AIzaSyCk6NNWO7DxVUEyEW1B6m-YNpdqv5HbyEk"];
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedUrlAsString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:set];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithURL:[NSURL URLWithString:encodedUrlAsString]
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

            NSLog(@"RESPONSE: %@",response);
            NSString *resSrt = [[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
            NSLog(@"DATA: %@",resSrt);

            if (!error) {
            // Success
            if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSError *jsonError;
            json =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
         dispatch_sync(dispatch_get_main_queue(), ^{

              NSArray *routesArray = [json objectForKey:@"routes"];
              NSLog(@"succes===== %@",routesArray);
              GMSPolyline *polyline = nil;

              if ([routesArray count] > 0)
              {
              NSDictionary *routeDict = [routesArray objectAtIndex:0];
             NSDictionary *routeOverviewPolyline = [routeDict objectForKey:@"overview_polyline"];
             points = [routeOverviewPolyline objectForKey:@"points"];
             NSLog(@"points ==== %@",points);



             GMSPath *path = [GMSPath pathFromEncodedPath:points];
             polyline = [GMSPolyline polylineWithPath:path];
             GMSPolyline *polyline = [GMSPolyline polylineWithPath:path];
             polyline.strokeWidth = 5;
             polyline.strokeColor=[UIColor redColor];
             polyline.map = self.map_view;
             }
              else
             {

             }
              });

             }
            else {
                    //Web server is returning an error
                }
            }

            else {
                // Fail
                NSLog(@"error : %@", error.description);
            }

        }] resume];

      }

That code used after error show

In this code and in this line polyline.map = self.map_view; are commented and run then no error. This line No comment and run then show error. -[MKMapView updateOverlay:]

Navigator issue : In this line polyline.map = self.map_view; Incompatible pointer types assigning to 'GMSMapView * _Nullable' from 'MKMapView *'

Please suggest how to draw PolyLine. Thankyou

Upvotes: 0

Views: 1642

Answers (2)

jia ma
jia ma

Reputation: 198

Check if the type of self.map_view is GMSMapView or not?

Upvotes: 0

Keyur Akbari
Keyur Akbari

Reputation: 167

Used this code. it's work well for me.

-(void)setMapDataValue
    {
        [googleMapView clear];
        NSString *strUrl = [self getDirectionsUrl];
        [self serviceCalledToGetRouteFromCoordinate:strUrl];
    }

-(NSString*)getDirectionsUrl{

    // Origin of route
    NSString *str_origin = [NSString stringWithFormat:@"origin=%f,%f",sourcePosition.latitude, sourcePosition.longitude];

    // Destination of route
    NSString *str_dest = [NSString stringWithFormat:@"destination=%f,%f",destinationPosition.latitude, destinationPosition.longitude];

    // Sensor enabled
    NSString *sensor = @"sensor=false";

    // Building the parameters to the web service
    NSString *parameters = [NSString stringWithFormat:@"%@&%@&%@",str_origin,str_dest,sensor];

    // Output format
    NSString *output = @"json";

    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/%@?%@",output,parameters];

    return url;
}

-(void)serviceCalledToGetRouteFromCoordinate:(NSString *)strUrl
{
    if([[AFNetworkReachabilityManager sharedManager] isReachable])
    {
        DLog(@"URL: %@", strUrl);

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

        [manager.operationQueue cancelAllOperations];

        [manager GET:strUrl parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject)
         {
             if([[responseObject[@"status"] lowercaseString] isEqualToString:@"ok"] && [responseObject[@"routes"] count]>0)
             {
                 arrLocation = responseObject[@"routes"][0][@"legs"][0][@"steps"];
             }
             [self setMapView];
         }
             failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
         {
             DLog(@"Error: %@", error);
         }];
    }
    else
    {
        [self.view endEditing:YES];
        [Utility displayAlertWithTitle:NSLocalizedString(@"no_internet_connection", nil) andMessage:NSLocalizedString(@"internet_appears_offline", nil)];
    }
}

-(void)setMapView
{
    if (arrLocation.count > 0) {
        sourcePosition.latitude = [[[[arrLocation objectAtIndex:0] valueForKey:@"start_location"] valueForKey:@"lat"] floatValue];
        sourcePosition.longitude = [[[[arrLocation objectAtIndex:0] valueForKey:@"start_location"] valueForKey:@"lng"] floatValue];

        destinationPosition.latitude = [[[[arrLocation objectAtIndex:arrLocation.count-1] valueForKey:@"end_location"] valueForKey:@"lat"] floatValue];
        destinationPosition.longitude = [[[[arrLocation objectAtIndex:arrLocation.count-1] valueForKey:@"end_location"] valueForKey:@"lng"] floatValue];
    }

    [self setAnnotationInMapview:sourcePosition.latitude longitude:sourcePosition.longitude pinImgName:@"ic_loc_pin_red"];
    [self setAnnotationInMapview:destinationPosition.latitude longitude:destinationPosition.longitude pinImgName:@"ic_loc_pin_green"];


    if (arrLocation.count == 0)
    {
        GMSMutablePath *path = [GMSMutablePath path];
        [path addCoordinate:CLLocationCoordinate2DMake(sourcePosition.latitude,sourcePosition.longitude)];
        [path addCoordinate:CLLocationCoordinate2DMake(destinationPosition.latitude,destinationPosition.longitude)];

        GMSPolyline *rectangle = [GMSPolyline polylineWithPath:path];
        //        rectangle.strokeWidth = 2.f;
        rectangle.map = googleMapView;
    }
    else
    {
        for (int i = 0; i<arrLocation.count; i++)
        {
            NSString *strPolyline = arrLocation[i][@"polyline"][@"points"];
            GMSPolyline *polyline = [self polylineWithEncodedString:strPolyline];
            // Add the polyline to the map.
            //        polyline.strokeColor = [UIColor redColor];
            //        polyline.strokeWidth = 2.f;
            polyline.map = googleMapView;
        }
    }


}

-(void)setAnnotationInMapview:(float)newLatitude longitude:(float)newLongitude pinImgName:(NSString *)pinImgName
{
    CLLocationCoordinate2D position = CLLocationCoordinate2DMake(newLatitude, newLongitude);
    GMSMarker *marker = [GMSMarker markerWithPosition:position];
    marker.icon = [UIImage imageNamed:pinImgName];
    [marker setDraggable: YES];
    marker.map = googleMapView;
}

Upvotes: 1

Related Questions