【问题标题】:How to draw route between two locations and plot main points also using MapKit?如何使用 MapKit 在两个位置之间绘制路线并绘制要点?
【发布时间】:2012-09-19 08:08:48
【问题描述】:

我正在使用 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;  
}

但它不起作用。 ..

关于此的帮助 谢谢!...

【问题讨论】:

  • 为什么你不用UIWebView这个请求url,用户可以看到路由..
  • 我正在使用 mapview,我想在上面绘制路线
  • @vishy 但对于 ios6 ,它只是要求下载 ios 的谷歌地图应用程序

标签: iphone objective-c ios5 mapkit


【解决方案1】:

这个问题已经被问过好几次了。我猜你是从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

【讨论】:

    【解决方案2】:
    #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
    

    【讨论】:

    • 在不使用google api的情况下有没有其他方式显示路线?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 2011-01-08
    相关资源
    最近更新 更多