我无法让 MKPolygonRenderer 出现在我的地图上。我有一个MapViewController
包含 的类MKMapView
,并创建CustomMapOverlay
实例以在MKMapView
.
MapViewController.m:
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView.delegate = self;
self.mapView.showsUserLocation = YES;
}
// ...
// Later, I retrieve some models and generate CustomMapOverlay instances from them...
for (Model *model in models) {
CustomMapOverlay *customMapOverlay = [[CustomMapOverlay alloc] initWithModel:model];
[self.mapView addOverlay:customMapOverlay];
}
// ...
// Implement MKMapViewDelegate protocol
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
MKPolygonRenderer *polygonRenderer = [[MKPolygonRenderer alloc] initWithOverlay:overlay];
polygonRenderer.lineWidth = 2;
polygonRenderer.strokeColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0];
polygonRenderer.fillColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:0.5];
return polygonRenderer;
}
CustomMapOverlay.m:
@implementation CustomMapOverlay
// Required by MKOverlay protocol
@synthesize coordinate,
boundingMapRect;
- (instancetype)initWithModel:(Model *)model {
coordinate = CLLocationCoordinate2DMake(model.latitude, model.longitude);
double radiusInPoints = MKMapPointsPerMeterAtLatitude(model.latitude) * model.radius;
boundingMapRect = MKMapRectMake(model.latitude, model.longitude, radiusInPoints, radiusInPoints);
return self;
}
@end
mapView:rendererForOverlay
被调用,并检查overlay
调试器中coordinate
的它说它确实)。boundingMapRect
MKMapPointsPerMeterAtLatitude
但是,地图上没有出现多边形。
更新:
我现在意识到我正在尝试渲染多边形而不创建它们。CustomMapOverlay
那么,我现在正在生成MKPolygon
这样的叠加层,而不是:
CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(model.latitude, model.longitude);
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(centerCoordinate, model.radius, model.radius);
int numCoords = 4;
CLLocationCoordinate2D *coords = malloc(sizeof(CLLocationCoordinate2D) * numCoords);
coords[0] = CLLocationCoordinate2DMake((region.center.longitude - 0.5*region.span.longitudeDelta), (region.center.latitude + 0.5*region.span.latitudeDelta));
coords[1] = CLLocationCoordinate2DMake((region.center.longitude + 0.5*region.span.longitudeDelta), (region.center.latitude + 0.5*region.span.latitudeDelta));
coords[2] = CLLocationCoordinate2DMake((region.center.longitude + 0.5*region.span.longitudeDelta), (region.center.latitude - 0.5*region.span.latitudeDelta));
coords[3] = CLLocationCoordinate2DMake((region.center.longitude - 0.5*region.span.longitudeDelta), (region.center.latitude - 0.5*region.span.latitudeDelta));
MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coords count:numCoords];
free(coords);
[self.mapView addOverlay:polygon];
但是,现在mapView:rendererForOverlay
根本不再被调用。