在Mapview iOS 6中绘制折线 [英] Draw polyline in mapview iOS 6

查看:74
本文介绍了在Mapview iOS 6中绘制折线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在做一个必须显示路线图的应用程序.我解析了一个Json以获得绘制折线的点.我在网上找到了绘制此折线的代码.我发现的代码位于此链接上: http://iosguy.com /2012/05/22/tracing-routes-with-mapkit/

Hi I'm doing an app that must to show a map with the route. I parsed a Json to obtain the points to draw the polyline. I found a a code in the web to draw this polyline. The code I found it's on this link: http://iosguy.com/2012/05/22/tracing-routes-with-mapkit/

在显示创建MKPolyline批注"的地方,我试图将其导入应用程序,但是在创建坐标数组时遇到了问题.我的方法是这样:

Where it says "Create the MKPolyline annotation" I tried to import this in my app, but I'm having problems to create the array of the coordinates. My method is this:

- (void)createMKpolylineAnnotation {
NSInteger numberOfSteps = self.path.count;

CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * numberOfSteps);
for (NSInteger index = 0; index < numberOfSteps; index++) {
    CLLocation *location = [self.path objectAtIndex:index];
    CLLocationCoordinate2D coordinate = location.coordinate;
    coords[index] = coordinate;
}

MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coords count:numberOfSteps];
[self.mapView addOverlay:polyLine];
}

当我尝试仅初次设置coords的值时,为什么会这样? 您能帮我解决这个问题还是我应该改用其他方式?

When I try to look the value of coords is setted only the first time, why's that? Can you help me to solve this problem or i should make in another mode?

我在这里发布用于处理地图视图的视图控制器的代码.

I post here the code of the view controller that handle the map view.

MapViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>

@interface MapViewController : UIViewController <MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

@property (nonatomic, strong) NSString *fromCity;
@property (nonatomic, strong) NSString *toCity;

- (IBAction)chooseKindOfMap:(id)sender;
@end

MapViewController.m

#import "MapViewController.h"
#import "AppDelegate.h"
#import "PlaceAnnotation.h"

@interface MapViewController ()

@property (nonatomic, strong)NSMutableArray *mapAnnotation;
@property (nonatomic) BOOL needUpdateRegion;
@property (nonatomic, strong)NSMutableArray *path;

@end

@implementation MapViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self parseGoogleJsonToObtainPointsForPolyline];
    [self.mapView setDelegate:self];
    self.needUpdateRegion = YES;
    //[self centerMap];
    self.mapAnnotation = [[NSMutableArray alloc]initWithCapacity:2];
    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    NSLog(@"%d", appDelegate.dataForMap.count);
    NSArray* coords = [self getCoords:appDelegate.dataForMap];
    NSLog(@"coords = %@", coords);
    PlaceAnnotation *fromPlace = [[PlaceAnnotation alloc] initWithCoordinateAndName:coords[0] andLong:coords[1] andName:self.fromCity];
    PlaceAnnotation *toPlace = [[PlaceAnnotation alloc] initWithCoordinateAndName:coords[2] andLong:coords[3] andName:self.toCity];

    [self.mapAnnotation insertObject:fromPlace atIndex:0];
    [self.mapAnnotation insertObject:toPlace atIndex:1];
    NSLog(@"mapAnnotation.count: %d", self.mapAnnotation.count);

    if (self.mapAnnotation) {
        [self.mapView removeAnnotations:self.mapView.annotations];
    }

    [self.mapView addAnnotation:self.mapAnnotation[0]];
    [self.mapView addAnnotation:self.mapAnnotation[1]];
    NSLog(@"MapAnnotation = %@", self.mapView.annotations);
    [self updateRegion];
    [self createMKpolylineAnnotation];
}

//- (void)viewDidAppear:(BOOL)animated {
//    [super viewDidAppear:animated];
//    if (self.needUpdateRegion) [self updateRegion];
//}


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

- (MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    pin.pinColor = MKPinAnnotationColorRed;
    return pin;
}

- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    MKPinAnnotationView *ulv = [mapView viewForAnnotation:mapView.userLocation];
    ulv.hidden = YES;
}

- (NSArray*)getCoords:(NSDictionary*)data {
    NSArray *legs = [data objectForKey:@"legs"];
    NSDictionary *firstZero = [legs objectAtIndex:0];
    NSDictionary *endLocation = [firstZero objectForKey:@"end_location"];
    NSDictionary *startLocation = [firstZero objectForKey:@"start_location"];
    NSString *latFrom = [startLocation objectForKey:@"lat"];
    NSString *lngFrom = [startLocation objectForKey:@"lng"];
    NSString *latTo = [endLocation objectForKey:@"lat"];
    NSString *lngTo = [endLocation objectForKey:@"lng"];
    return @[latFrom,lngFrom,latTo,lngTo];
}

- (void)centerMap {
    MKCoordinateRegion region;
    region.center.latitude = 41.178654;
    region.center.longitude = 11.843262;
    region.span.latitudeDelta = 11.070406;
    region.span.longitudeDelta = 12.744629;

    [self.mapView setRegion:region];
}

- (IBAction)chooseKindOfMap:(id)sender {
    if ([sender tag] == 0) {
        self.mapView.mapType = MKMapTypeStandard;
    }
    if ([sender tag] == 1) {
        self.mapView.mapType = MKMapTypeSatellite;
    }
    if ([sender tag] == 2) {
        self.mapView.mapType = MKMapTypeHybrid;
    }
}

- (void)updateRegion
{
    self.needUpdateRegion = NO;
    CGRect boundingRect;
    BOOL started = NO;
    for (id <MKAnnotation> annotation in self.mapView.annotations) {
        CGRect annotationRect = CGRectMake(annotation.coordinate.latitude, annotation.coordinate.longitude, 0, 0);
        if (!started) {
            started = YES;
            boundingRect = annotationRect;
        } else {
            boundingRect = CGRectUnion(boundingRect, annotationRect);
        }
    }
    if (started) {
        boundingRect = CGRectInset(boundingRect, -0.2, -0.2);
        if ((boundingRect.size.width < 20) && (boundingRect.size.height < 20)) {
            MKCoordinateRegion region;
            region.center.latitude = boundingRect.origin.x + boundingRect.size.width / 2;
            region.center.longitude = boundingRect.origin.y + boundingRect.size.height / 2;
            region.span.latitudeDelta = boundingRect.size.width;
            region.span.longitudeDelta = boundingRect.size.height;
            [self.mapView setRegion:region animated:YES];
        }
    }
}

- (void)parseGoogleJsonToObtainPointsForPolyline {
    NSDictionary *polyline;
    NSMutableArray *points = [[NSMutableArray alloc]init];;

    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    NSArray *legs = [appDelegate.dataForMap objectForKey:@"legs"];
    NSDictionary *firstZero =[legs objectAtIndex:0];
    NSArray *steps = [firstZero objectForKey:@"steps"];
    for (int i = 0; i < steps.count; i++) {
        polyline = [steps[i] objectForKey:@"polyline"];
        [points addObject:polyline[@"points"]];
        NSLog(@"POINTS = %@", polyline[@"points"]);
        self.path = [self decodePolyLine:points[i]];
    }
    NSLog(@"path = %@", self.path);
}

-(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];

        CLLocation *location = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
        [array addObject:location];
    }

    return array;
}

- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay {
    MKPolylineView *polylineView = [[MKPolylineView alloc] initWithPolyline:overlay];
    polylineView.strokeColor = [UIColor redColor];
    polylineView.lineWidth = 1.0;

    return polylineView;
}

- (void)createMKpolylineAnnotation {
    NSInteger numberOfSteps = self.path.count;

    CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * numberOfSteps);
    for (NSInteger index = 0; index < numberOfSteps; index++) {
        CLLocation *location = [self.path objectAtIndex:index];
        CLLocationCoordinate2D coordinate = location.coordinate;
        coords[index] = coordinate;
    }

    MKPolyline *polyLine = [MKPolyline polylineWithCoordinates:coords count:numberOfSteps];
    [self.mapView addOverlay:polyLine];
}
@end

我使用AppDelegate拥有了Json(我在另一个类中对其进行了解析)

I used the AppDelegate to have the Json (I parsed it in another class)

推荐答案

此处是教程如何将折线添加到mapView.希望这会有所帮助!

Here is a tutorial how to add a polyline to a mapView. Hope this helps!

不幸的是,上面提供的链接现在已断开,我找不到所引用的教程.

Unfortunately, the link provided above is now broken, and I am not able to find the tutorial referred to.

这篇关于在Mapview iOS 6中绘制折线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆