IOS6 IOS7 Mapkit draw Rout(地图划线)

IOS7  比较简单

    CLLocationCoordinate2D  _start2D;

    CLLocationCoordinate2D  _end2D;

 NSArray *_routes;

IOS6

需要文件  ....google

#import "RegexKitLite.h"

   UIImageView *  _routeView;

    NSArray *_routes;

load

   if (IOS7) {
//      [_mapView setRegion:MKCoordinateRegionMake(_start2D, MKCoordinateSpanMake(0.05, 0.05))];
        _routes = [self calculateRoutesFrom:_start2D to:_end2D] ;
        [self centerMap:_routes];
        //    //规划地图路径
       [self requestRoutWithSoure:_start2D Destination:_end2D];
    }else
    {
        _routeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _mapView.frame.size.width, _mapView.frame.size.height)];
        
        _routeView.userInteractionEnabled = NO;
        [_mapView addSubview:_routeView];
        if(_routes) {
            [_mapView removeAnnotations:[_mapView annotations]];
        }
        _routes = [self calculateRoutesFrom:_start2D to:_end2D] ;
        //根据数组画线
        [self updateRouteView:_routes RouteView:_routeView];
        //根据线路确定呈现范围
        [self centerMap:_routes];
    }

 

 

 

ios7路径规划

#pragma mark - 请求路径
-(void)requestRoutWithSoure:(CLLocationCoordinate2D) start2D  Destination:(CLLocationCoordinate2D)end2D
{
    MKDirectionsRequest *directionsRequest = [[MKDirectionsRequest alloc] init];
    directionsRequest.transportType = MKDirectionsTransportTypeAutomobile;
    
    MKPlacemark *startMark = [[MKPlacemark    alloc] initWithCoordinate:start2D addressDictionary:nil];
    MKPlacemark *endMark = [[MKPlacemark    alloc] initWithCoordinate:end2D addressDictionary:nil];
    
    MKMapItem *startItem = [[MKMapItem alloc] initWithPlacemark:startMark];
    MKMapItem *endItem = [[MKMapItem alloc] initWithPlacemark:endMark];
    
    [directionsRequest setSource:startItem];
    [directionsRequest setDestination:endItem];
    
    MKDirections *directions = [[MKDirections alloc] initWithRequest:directionsRequest];
    //接收rout
    [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
        
        if (!response) {
            return ;
        }
        _routes  = [response routes];
        [_routes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            MKRoute *rout = obj;
            MKPolyline *line = [rout polyline];
            [_mapView addOverlay:line];
        }];
        //根据 routes  数据 确定region的呈现范围
        //[self centerMap:_routes];

        
    }];
}

ios7 回调

#pragma mark - ios7  mapView delegate
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKAnnotationView *annView;
    if (annotation == _startPoint) {
        //标注
        annView = [[MKAnnotationView alloc] initWithAnnotation:_startPoint reuseIdentifier:@"_start2D"];
        annView.image= [UIImage imageNamed:@"start_location"];

    }
    if (annotation == _endPoint) {
        annView = [[MKAnnotationView alloc] initWithAnnotation:_endPoint reuseIdentifier:@"_end2D"];
        
        annView.image= [UIImage imageNamed:@"end_location"];
    }
    
    return annView;
}

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithOverlay:overlay];
    renderer.strokeColor = lineColor;
    renderer.lineWidth = lineW;
    return  renderer;
}

 


 IOS6 路径规划 画线

#pragma mark - ios6 mapView

-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t {
    
    NSString* saddr;
    NSString* daddr;
    
    saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];
    daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];
    
    
    NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.google.com/maps?output=dragdir&saddr=%@&daddr=%@", saddr, daddr];
    
    NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
    NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:nil];
    
    NSString *encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];
    
    return [self decodePolyLine:[encodedPoints mutableCopy]:f to:t];
}
//解码
-(NSMutableArray *)decodePolyLine: (NSMutableString *)encoded :(CLLocationCoordinate2D)f to: (CLLocationCoordinate2D) t {
    [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];
        CLLocation *loc = [[CLLocation alloc] initWithLatitude:[latitude floatValue]
                                                     longitude:[longitude floatValue]];
        [array addObject:loc];
    }
    CLLocation *first = [[CLLocation alloc] initWithLatitude:[[NSNumber numberWithFloat:f.latitude] floatValue]
                                                   longitude:[[NSNumber numberWithFloat:f.longitude] floatValue] ];
    CLLocation *end = [[CLLocation alloc] initWithLatitude:[[NSNumber numberWithFloat:t.latitude] floatValue]
                                                 longitude:[[NSNumber numberWithFloat:t.longitude] floatValue] ];
    [array insertObject:first atIndex:0];
    [array addObject:end];
    
    return array;
}
//用routes数组的内容 确定region的呈现范围
-(void) centerMap:(NSArray *)routesArr {
    MKCoordinateRegion region;
    
    CLLocationDegrees maxLat = -90;
    CLLocationDegrees maxLon = -180;
    CLLocationDegrees minLat = 90;
    CLLocationDegrees minLon = 180;
    for(int idx = 0; idx < routesArr.count; idx++)
    {
        CLLocation* currentLocation = [routesArr objectAtIndex:idx];
        if(currentLocation.coordinate.latitude > maxLat)
            maxLat = currentLocation.coordinate.latitude;
        if(currentLocation.coordinate.latitude < minLat)
            minLat = currentLocation.coordinate.latitude;
        if(currentLocation.coordinate.longitude > maxLon)
            maxLon = currentLocation.coordinate.longitude;
        if(currentLocation.coordinate.longitude < minLon)
            minLon = currentLocation.coordinate.longitude;
    }
    region.center.latitude     = (maxLat + minLat) / 2;
    region.center.longitude    = (maxLon + minLon) / 2;
    region.span.latitudeDelta  = maxLat - minLat;
    region.span.longitudeDelta = maxLon - minLon;
    
    [_mapView setRegion:region animated:YES];
}

//用routes数组的内容  在 UIImageView 上画线
-(void) updateRouteView:(NSArray *)routesArr RouteView:(UIImageView *)routeImg {
    CGContextRef context = CGBitmapContextCreate(nil,
                                                 routeImg.frame.size.width,
                                                 routeImg.frame.size.height,
                                                 8,
                                                 4 * routeImg.frame.size.width,
                                                 CGColorSpaceCreateDeviceRGB(),
                                                 kCGImageAlphaPremultipliedLast);
    
    CGContextSetStrokeColorWithColor(context, lineColor.CGColor);
    CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);
    CGContextSetLineWidth(context, lineW);
    
    for(int i = 0; i < routesArr.count; i++) {
        CLLocation* location = [routesArr objectAtIndex:i];
        CGPoint point = [_mapView convertCoordinate:location.coordinate toPointToView:routeImg];
        
        if(i == 0) {
            CGContextMoveToPoint(context, point.x, routeImg.frame.size.height - point.y);
        } else {
            CGContextAddLineToPoint(context, point.x, routeImg.frame.size.height - point.y);
        }
    }
    
    CGContextStrokePath(context);
    
    CGImageRef image = CGBitmapContextCreateImage(context);
    UIImage* img = [UIImage imageWithCGImage:image];
    
    routeImg.image = img;
    CGContextRelease(context);
    
}

#pragma mark mapView delegate functions
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
{

    if (!IOS7)


    _routeView.hidden = YES;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{

    if (!IOS7){


    [self updateRouteView:_routes RouteView:_routeView];
    _routeView.hidden = NO;
    [_routeView setNeedsDisplay];
} }

 

 

posted @ 2014-03-27 17:05  hhhker  阅读(2557)  评论(1编辑  收藏  举报