自定义MKOverlay,半径为米

时间:2013-12-25 01:14:28

标签: ios mkmapview mkoverlay mkoverlaypathrenderer

我通过创建一个符合MKOverlay协议和MKOverlayPathRenderer子类的NSObject子类来进行自定义覆盖。我的目标是在MKMapView上制作一个固定在用户位置的圆形叠加层,我的工作正常。每当我的叠加层上的坐标被设置时,我的渲染器,使用键值观察,使它绘制的路径无效,然后重绘。

我遇到的问题是我希望圆的半径以米为单位,但我不认为我正在做正确的数学运算或者我缺少的东西。我在下面发布了覆盖对象和渲染器的源代码(渲染器的界面中没有任何内容)。举个例子,我将半​​径设置为200米,但在地图视图中,它只显示为大约10米。任何人都知道如何解决这个问题?

//Custom Overlay Object Interface
@import Foundation;
@import MapKit;
@interface CustomRadiusOverlay : NSObject <MKOverlay>

+ (id)overlayWithCoordinate:(CLLocationCoordinate2D)coordinate radius:(CLLocationDistance)radius;

@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic) MKMapRect boundingMapRect;
@property (nonatomic) CLLocationDistance radius;

@end

//Custom overlay
#import "CustomRadiusOverlay.h"

@implementation LFTRadiusOverlay

+ (id)overlayWithCoordinate:(CLLocationCoordinate2D)coordinate radius:(CLLocationDistance)radius{
CustomRadiusOverlay* overlay = [LFTRadiusOverlay new];
    overlay.coordinate = coordinate;
    overlay.radius = radius;
    return overlay;
}

- (MKMapRect)boundingMapRect{
    MKMapPoint upperLeft = MKMapPointForCoordinate(self.coordinate);
    MKMapRect bounds = MKMapRectMake(upperLeft.x, upperLeft.y, self.radius*2, self.radius*2);
    return bounds;
}

- (void)setCoordinate:(CLLocationCoordinate2D)coordinate{
    _coordinate = coordinate;
    self.boundingMapRect = self.boundingMapRect;
}

@end


#import "CustomOverlayRadiusRenderer.h"
#import "CustomRadiusOverlay.h"

@interface CustomOverlayRadiusRenderer()

@property (nonatomic) CustomRadiusOverlay* circleOverlay;

@end

@implementation CustomOverlayRadiusRenderer

- (id)initWithOverlay:(id<MKOverlay>)overlay{
    self = [super initWithOverlay:overlay];
    if(self){
        _circleOverlay = (LFTRadiusOverlay*)overlay;
        [_circleOverlay addObserver:self forKeyPath:@"coordinate" options:NSKeyValueObservingOptionNew context:NULL];
        self.fillColor = [UIColor redColor];
        self.alpha = .7f;
    }
    return self;
}

- (void)createPath{
    CGMutablePathRef path = CGPathCreateMutable();
    MKMapPoint mapPoint = MKMapPointForCoordinate(self.circleOverlay.coordinate);
    CGPoint point = [self pointForMapPoint:mapPoint];
    CGPathAddArc(path, NULL, point.x, point.y, self.circleOverlay.radius, 0, kDegreesToRadians(360), YES);
    self.path = path;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    [self invalidatePath];
}
@end

1 个答案:

答案 0 :(得分:5)

您绘制米(作为半径),但您需要在MapPoints中指定所有内容。

所以转换单位:

~~ mapPoints = meters * MKMapPointsPerMeterAtLatitude(coordinate.latitude)