给折线定义坐标,然后把折线加到地图上
<br />
代码中locations
是存放了地图经纬度的一些点。
官方给出了2个API
- 方法一:<br />
+ (instancetype)polylineWithPoints:(MKMapPoint *)points <br />count:(NSUInteger)count;
MKMapPoint *arrayPoint = malloc(sizeof(MKMapPoint) * locations.count); // 这块必须动态分派内存,具体为什么,还不知道。用malloc分配内存在堆内分配内存,用完改变量后,必须手动释放内存。
for (int i = 0; i < locations.count; i++) {
CLLocation *location = [locations objectAtIndex:i];
MKMapPoint point = MKMapPointForCoordinate(location.coordinate);
arrayPoint[i] = point;
}
MKPolyline *line = [MKPolyline polylineWithPoints:arrayPoint count:locations.count];
[_mapView addOverlay:line];
free(arrayPoint);
- 方法二:<br />
+ (instancetype)polylineWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSUInteger)count;
CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * locations.count);
for (int i = 0; i < locations.count; i++) {
NSLog(@"%@",locations[i]);
CLLocation *location = locations[i];
coords[i] = [location coordinate];
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:coords count:locations.count];
[_mapView addOverlay:polyline];
free(coords);
*** 遗留问题 ***
之前尝试 MKMapPoint *arrayPoint[locations.count];
但是当程序执行到arrayPoint[i] = point;时,arrayPoint的值始终是nil,
始终不得其解,后来看了官网demo,给MKMapPoint
实例出的对象分派内存是这样的,malloc(sizeof(MKMapPoint) * locations.count);
改了之后,程序OK。
可能OC比较特殊吧,要求指针一定得是堆上的,栈里面的变量不行。Swift语言的话直接用数组就可以了。知道原因的大神,不吝赐教。
*** 注意事项 ***
malloc
动态分配内存,记得用完该变量记得free
掉
调用MKMapView
代理方法进行覆盖物加载
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolylineRenderer *overlayRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
overlayRenderer.strokeColor = [UIColor blueColor];
overlayRenderer.fillColor = [UIColor blueColor];
overlayRenderer.lineWidth = 3;
return overlayRenderer;
}
return nil;
}
iOS7 之前加载覆盖物划线用下面的方法<br />
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay ;
<br />
iOS7 之后该方法弃用,改用<br />
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay