使用Xcode 6.4和MapBox,无法绘制路线方向。

3

我正在使用MapBox为起点和终点绘制方向路线。

当我使用网站提供的示例URL时,我能够绘制路线。

但是当我使用自己的坐标时,我却无法绘制任何路线。

我没有收到任何错误消息或日志。

#import "ViewController.h"



@interface ViewController () 

{
    NSMutableData *_responseData;
    NSDictionary *_directionApiResponseDict;
    NSArray *_coordinatesArray;
    BOOL isControllerPoped;

}
@property (nonatomic) MGLMapView *mapView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // initialize the map view

   // NSURL *styleURL = [NSURL URLWithString:@"asset://styles/dark-v8.json"];
    self.mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds];

    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    self.mapView.delegate = self;



     //set the map's center coordinate
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(28.57,77.32)
                            zoomLevel:15
                             animated:NO];
    [self.view addSubview:self.mapView];

//    MGLPointAnnotation *point = [[MGLPointAnnotation alloc] init];
//    point.coordinate = CLLocationCoordinate2DMake(-122.42,37.78);
//    point.title = @"Hello world!";
//    point.subtitle = @"Welcome to The Ellipse.";
//    
//    // Add annotation `point` to the map
//    [self.mapView addAnnotation:point];

    NSString *urlString = [NSString stringWithFormat:@"https://api.mapbox.com/v4/directions/mapbox.driving/28.57,77.32;28.11,77.22.json?access_token=pk.eyJ1IjoicmFodWx2cyIsImEiOiJjaWdjN2w1c3YycWNxdmptM3YzNzR4dWR5In0.jU9egzoUg46b4fLUQlL-Bg"];

    //https://api.mapbox.com/v4/directions/mapbox.driving/-122.42,37.78;-77.03,38.91.json?alternatives=false&instructions=html&geometry=polyline&steps=false&&access_token=<your%20access%20token>  these co-ordinates works fine

    NSLog(@"URRRL=%@",urlString);

   NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];

    // Create url connection and fire request
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation {
    return YES;
}



#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [_responseData appendData:data];

}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {

    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    _directionApiResponseDict = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];


    NSArray *rootsDictArray = [_directionApiResponseDict valueForKey:@"routes"];
    if(rootsDictArray && rootsDictArray.count > 0)
    {
        NSDictionary *rootDict = [rootsDictArray objectAtIndex:0];
        if(rootDict && [rootDict valueForKey:@"geometry"])
        {
            NSDictionary *geoDict = [rootDict valueForKey:@"geometry"];

            if(geoDict && [geoDict isKindOfClass:[NSDictionary class]])
            {
                _coordinatesArray = [geoDict valueForKey:@"coordinates"];

                if(_coordinatesArray)
                {
                    [self drawPolyline];
                }
            }
        }
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

}


- (void)drawPolyline
{
    // Perform GeoJSON parsing on a background thread
    dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(backgroundQueue, ^(void)
                   {


                       // Get the raw array of coordinates for our line
                       NSArray *rawCoordinates = _coordinatesArray;
                       NSUInteger coordinatesCount = rawCoordinates.count;

                       // Create a coordinates array, sized to fit all of the coordinates in the line.
                       // This array will hold the properly formatted coordinates for our MGLPolyline.
                       CLLocationCoordinate2D coordinates[coordinatesCount];

                       int validCoordinates=0;
                       // Iterate over `rawCoordinates` once for each coordinate on the line
                       for (NSUInteger index = 0; index < coordinatesCount; index++)
                       {
                           // Get the individual coordinate for this index
                           NSArray *point = [rawCoordinates objectAtIndex:index];

                           // GeoJSON is "longitude, latitude" order, but we need the opposite

                           if([point count]>1){
                               CLLocationDegrees lat = [[point objectAtIndex:1] doubleValue];
                               CLLocationDegrees lng = [[point objectAtIndex:0] doubleValue];
                               CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(lat, lng);

                               // Add this formatted coordinate to the final coordinates array at the same index
                               coordinates[validCoordinates] = coordinate;
                               validCoordinates++;
                           }
                       }

                       // Create our polyline with the formatted coordinates array
                       MGLPolyline *polyline = [MGLPolyline polylineWithCoordinates:coordinates count:validCoordinates];

                       // Optionally set the title of the polyline, which can be used for:
                       //  - Callout view
                       //  - Object identification
                       // In this case, set it to the name included in the GeoJSON


                       // Add the polyline to the map, back on the main thread
                       // Use weak reference to self to prevent retain cycle
                       __weak typeof(self) weakSelf = self;
                       dispatch_async(dispatch_get_main_queue(), ^(void)
                                      {
                                          [weakSelf.mapView addAnnotation:polyline];
                                      });



                   });
}

- (CGFloat)mapView:(MGLMapView *)mapView alphaForShapeAnnotation:(MGLShape *)annotation
{
    // Set the alpha for all shape annotations to 1 (full opacity)
    return 1.0f;
}

- (CGFloat)mapView:(MGLMapView *)mapView lineWidthForPolylineAnnotation:(MGLPolyline *)annotation
{
    // Set the line width for polyline annotations
    return 2.0f;
}

- (UIColor *)mapView:(MGLMapView *)mapView strokeColorForShapeAnnotation:(MGLShape *)annotation
{
    // Set the stroke color for shape annotations
    // ... but give our polyline a unique color by checking for its `title` property
    if ([annotation.title isEqualToString:@"Crema to Council Crest"])
    {
        // Mapbox cyan
        return [UIColor colorWithRed:59.0f/255.0f green:178.0f/255.0f blue:208.0f/255.0f alpha:1.0f];
    }
    else
    {
        return [UIColor redColor];
    }
}


#pragma mark - Map Delegate methods


- (MGLAnnotationImage *)mapView:(MGLMapView *)mapView imageForAnnotation:(id <MGLAnnotation>)annotation {

    return nil;
    //
    //    MGLAnnotationImage *annotationImage = [mapView dequeueReusableAnnotationImageWithIdentifier:kImageIdentifire];
    //
    //    if ( ! annotationImage)
    //    {
    //        // Leaning Tower of Pisa by Stefan Spieler from the Noun Project
    //        UIImage *image = [UIImage imageNamed:@"annotation.png"];
    //        annotationImage = [MGLAnnotationImage annotationImageWithImage:image reuseIdentifier:kImageIdentifire];
    //    }
    //
    //    return annotationImage;

}



@end
2个回答

1

你可能会对Mapbox Swift方向工具包感兴趣:

https://github.com/mapbox/MapboxDirections.swift

这个功能类似于苹果的MKDirections。在Swift代码也在目标中后,您可以通过将自动生成的<TargetName>-Swift.h导入到您的Objective-C代码中来使用它。


1
你的Mapbox URL调用存在问题。
来自Mapbox API文档:
一个由分号分隔的经度,纬度坐标对列表按顺序访问,至少包含两个元素(起点和终点)。列表中可以有2到25个坐标对。
但是你把经度值作为了纬度值,把纬度值作为了经度值。基于你使用的CLLocationCoordinate2DMake方法调用,该方法具有以下参数:
CLLocationCoordinate2DMake(CLLocationDegrees纬度, CLLocationDegrees经度)
正如你所看到的,在Mapbox调用URL中,你应该先放经度,然后再放纬度。
在你的url中反转纬度和经度,一切都会没问题的。我在浏览器中测试了你的链接,我得到了方向。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接