3

我正在使用 MapKit api 获取地图上的当前位置并在放置针指向的两个位置之间绘制路线。我还想在其路线之间获取所有主要看台。我正在使用以下函数来获取两个位置之间的路线

- (NSArray*)getRoutePointFrom:(MyLocation*)origin to:(MyLocation*)destination
{
 NSString* saddr = [NSString stringWithFormat:@"%f,%f", origin.coordinate.latitude, origin.coordinate.longitude];
 NSString* daddr = [NSString stringWithFormat:@"%f,%f", destination.coordinate.latitude, destination.coordinate.longitude];


 NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false&avoid=highways&mode=driving",saddr,daddr]];

 NSError *error=nil;

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;

 [request setURL:url];
 [request setHTTPMethod:@"POST"];

  NSURLResponse *response = nil;

  NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: &error];

  NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

 SBJsonParser *json=[[SBJsonParser alloc] init];

 NSDictionary *dic=[json objectWithString:responseString error:nil];

 NSDictionary *nextdic=[dic valueForKey:@"routes"];
 NSDictionary *legdic=[nextdic valueForKey:@"legs"];
 NSDictionary *stepdic=[legdic valueForKey:@"steps"];

 NSArray *array=[[NSArray alloc] initWithArray:[[stepdic valueForKey:@"polyline"] valueForKey:@"points"]];  


 NSString *string=[NSString stringWithFormat:@"%@",[[array objectAtIndex:0] objectAtIndex:0]];




 return [self decodePolyLine:[string mutableCopy]];

}



-(NSMutableArray *)decodePolyLine:(NSString *)encodedStr 
{  

 NSMutableString *encoded = [[NSMutableString alloc] initWithCapacity:[encodedStr length]];  
 [encoded appendString:encodedStr];  
 [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"  
                             options:NSLiteralSearch  
                               range:NSMakeRange(0, [encoded length])];  
 NSInteger len = [encoded length];  

 NSInteger index = 0;  
 NSMutableArray *array = [[NSMutableArray alloc] init] ;  
 NSInteger lat=0;  
 NSInteger lng=0;  
 while (index < len) {  
  NSInteger b;  
  NSInteger shift = 0;  
  NSInteger result = 0;  
  do {  
   b = [encoded characterAtIndex:index++] - 63;  
   result |= (b & 0x1f) << shift;  
   shift += 5;  
  } while (b >= 0x20);  
  NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));  
  lat += dlat;  
  shift = 0;  
  result = 0;  
  do {  
   b = [encoded characterAtIndex:index++] - 63;  
   result |= (b & 0x1f) << shift;  
   shift += 5;  
  } while (b >= 0x20);  
  NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));  
  lng += dlng;  
  NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];  
  NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];  
  //          printf("[%f,", [latitude doubleValue]);  
  //          printf("%f]", [longitude doubleValue]);  
  CLLocation *loc =[[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]] ;  
  [array addObject:loc];  
 }  

 NSLog(@"array in decode polygon is %@",array);

 return array;  
}

但它不工作。..

关于这个的帮助谢谢!...

4

2 回答 2

5

这个问题已经被问过好几次了。我猜您正在从http://iosguy.com/2012/05/22/tracing-routes-with-mapkit/获取代码 您还可以查看那个 SO 问题:Plotting Route with Multiple Points in iOS

您也可以从http://iosboilerplate.com获取代码并为其做出贡献。

最后但并非最不重要的一点是,有一个框架可以帮助您以一小笔钱来完成它(但与您需要做的相比没有什么): http: //www.cocoacontrols.com/controls/ mtdirectionskit

于 2012-09-19T09:19:20.257 回答
4
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>


@interface ViewController : UIViewController<MKMapViewDelegate>
{
    NSData *alldata;
    NSMutableDictionary *data1;

    NSMutableArray *RouteLocation;
    NSMutableArray *RouteName;
}
@property (strong, nonatomic) IBOutlet MKMapView *mapview;
@property (nonatomic, retain) MKPolyline *routeLine;
@property (nonatomic, retain) MKPolylineView *routeLineView;

-(void)LoadMapRoute;
@end



#import "ViewController.h"



@implementation ViewController
@synthesize mapview,routeLine,routeLineView;

- (void)viewDidLoad {
    [super viewDidLoad];
     self.mapview.delegate = self;
    // Do any additional setup after loading the view, typically from a nib.
    RouteName = [[NSMutableArray alloc] initWithObjects:@"Ahmedabad",@"Rajkot", nil];
    RouteLocation = [[NSMutableArray alloc] initWithObjects:@"23.0300,72.5800",@"22.3000,70.7833", nil];
    [self LoadMapRoute];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//-------------------------------------
// ************* Map ******************
//-------------------------------------

-(void)LoadMapRoute
{
    MKCoordinateSpan span = MKCoordinateSpanMake(0.8, 0.8);
    MKCoordinateRegion region;
    region.span = span;
    region.center= CLLocationCoordinate2DMake(23.0300,72.5800);


    // Distance between two address
    NSArray *coor1=[[RouteLocation objectAtIndex:0] componentsSeparatedByString:@","];
    CLLocation *locA = [[CLLocation alloc] initWithLatitude:[[coor1 objectAtIndex:0] doubleValue] longitude:[[coor1 objectAtIndex:1] doubleValue]];

    NSArray *coor2=[[RouteLocation objectAtIndex:1] componentsSeparatedByString:@","];
    CLLocation *locB = [[CLLocation alloc] initWithLatitude:[[coor2 objectAtIndex:0] doubleValue] longitude:[[coor2 objectAtIndex:1] doubleValue]];
    CLLocationDistance distance = [locA distanceFromLocation:locB];
    NSLog(@"Distance :%.0f Meters",distance);


    NSString *baseUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=true", [RouteLocation objectAtIndex:0],[RouteLocation objectAtIndex:1] ];

    NSURL *url = [NSURL URLWithString:baseUrl];
    alldata = [[NSData alloc] initWithContentsOfURL:url];

    NSError *err;
    data1 =[NSJSONSerialization JSONObjectWithData:alldata options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&err];

    NSString *overviewPolyline = [[[[data1 objectForKey:@"routes"] objectAtIndex:0] objectForKey:@"overview_polyline"] objectForKey:@"points"];
    NSArray *path = [self decodePolyLine:overviewPolyline];



    if (err)
    {
        NSLog(@" %@",[err localizedDescription]);
    }



    NSInteger numberOfSteps = path.count;

    CLLocationCoordinate2D coordinates[numberOfSteps];
    for (NSInteger index = 0; index < numberOfSteps; index++) {
        CLLocation *location = [path objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;

        coordinates[index] = coordinate;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coordinates count:numberOfSteps];
    [self.mapview addOverlay:polyLine];


//    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:path count: path.count];
//    [self.mapview addOverlay:polyLine];
//    [self.mapview setRegion:region animated:YES];
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor colorWithRed:204/255. green:45/255. blue:70/255. alpha:1.0];
    polylineView.lineWidth = 5;

    return polylineView;
}


-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded {
    [encoded replaceOccurrencesOfString:@"\\\\" withString:@"\\"
                                options:NSLiteralSearch
                                  range:NSMakeRange(0, [encoded length])];
    NSInteger len = [encoded length];
    NSInteger index = 0;
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSInteger lat=0;
    NSInteger lng=0;
    while (index < len) {
        NSInteger b;
        NSInteger shift = 0;
        NSInteger result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lat += dlat;
        shift = 0;
        result = 0;
        do {
            b = [encoded characterAtIndex:index++] - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        NSInteger dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
        lng += dlng;
        NSNumber *latitude = [[NSNumber alloc] initWithFloat:lat * 1e-5];
        NSNumber *longitude = [[NSNumber alloc] initWithFloat:lng * 1e-5];
        printf("[%f,", [latitude doubleValue]);
        printf("%f]", [longitude doubleValue]);
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
        [array addObject:loc];
    }

    return array;
}
@end
于 2017-02-27T08:58:51.120 回答