【问题标题】:How to draw GMSPolyline in MapView如何在 MapView 中绘制 GMSPolyline
【发布时间】:2017-01-23 09:12:45
【问题描述】:

我创建了一个基于地图的应用程序。现在通过谷歌方向 api 获取折线点。但是如何用这个GSMPath 绘制折线。我尝试了很多次,但没有在GMSMapView 中绘制折线。怎么画请指教。 请指导使用哪些方法。

-(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; 从 'MKMapView *' 分配给 'GMSMapView * _Nullable' 的指针类型不兼容

请建议如何绘制折线。谢谢你

【问题讨论】:

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


    【解决方案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;
    }
    

    【讨论】:

    • 感谢回复 但是没有使用 AFHTTPNetwork 设置。因为我尝试但未在 Xcode 中成功设置。
    • 无需设置 AFHTTPNetwork。只需调用您的服务调用方法来调用上述服务并获取响应数组。我已经在我的实时项目中使用了这个代码,它工作得很好。别忘了给个评价。
    • 你的 -(void)setMapDataValue 哪个时间调用 InViewDidLoad?
    • 我正在使用您的代码,但请帮忙?如何在你的项目中声明sourcePosition.latitude
    • sourcePosition 是 CLLocationCoordinate2D 的对象。您可以将其声明为 @property (nonatomic) CLLocationCoordinate2D sourcePosition;
    【解决方案2】:

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

    【讨论】:

    • 供您参考 我的self.map_view 是 UIMapView 是否正确?
    • 请回复。我很累。请帮忙:(
    • GMSPolyline 应该使用 GMSMapView
    猜你喜欢
    • 1970-01-01
    • 2015-09-15
    • 2012-06-10
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多