如何在MapView中绘制GMSPolyline

时间:2017-01-23 09:12:45

标签: ios objective-c google-maps mkmapview gmsmapview

我已经创建了一个基于地图的应用。现在通过谷歌方向api获取PolyLine点数。但是如何使用此GSMPath绘制多边形线。我尝试了多次,但没有在GMSMapView中绘制polyLine。如何绘制请建议。 使用哪种方法请指导。

-(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];

      }

错误显示后使用的代码

在此代码中以及此行中polyline.map = self.map_view; 被评论并运行然后没有错误。 此行没有评论并运行然后显示错误。 -[MKMapView updateOverlay:]

导航器问题:在这一行polyline.map = self.map_view; 不兼容的指针类型分配给' GMSMapView * _Nullable'来自' MKMapView *'

请建议如何绘制PolyLine。谢谢你

2 个答案:

答案 0 :(得分:1)

使用此代码。它对我有用。

-(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;
}

答案 1 :(得分:0)

检查self.map_view的类型是否为GMSMapView