我通过制作符合 MKOverlay 协议(protocol)的 NSObject 子类和 MKOverlayPathRenderer 的子类来制作自定义叠加层。我的目标是在 MKMapView 上制作一个 anchor 定到用户位置的圆形叠加层,我让它工作得很好。每当我的叠加层上的坐标被设置时,我的渲染器使用键值观察使它绘制的路径无效,然后重新绘制。
我遇到的问题是我希望圆的半径以米为单位,但我认为我的数学计算不正确,或者我遗漏了一些东西。我在下面发布了覆盖对象和渲染器的源代码(渲染器的接口(interface)中没有任何内容)。举个例子,我将半径设置为 200 米,但在 map View 中,它只显示为大约 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
最佳答案
您绘制米(作为半径),但您需要在 MapPoints 中指定所有内容。
所以转换单位:
~~ mapPoints = meters * MKMapPointsPerMeterAtLatitude(coordinate.latitude)
关于ios - 半径以米为单位的自定义 MKOverlay,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20768261/