MapKit叠加层不会出现

时间:2016-04-08 05:21:50

标签: ios xcode swift mapkit

我正在尝试为地图添加圆形叠加层。我按照苹果文档进行了操作,但是当我运行应用程序时,叠加层没有出现。这是我的代码......

@IBOutlet var map: MKMapView!
let location = CLLocationCoordinate2DMake(40.73085, -73.99750)
let regionRadius: CLLocationDistance = 5500

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    let diskRenderer: MKCircleRenderer = MKCircleRenderer.init()
    diskRenderer.fillColor = UIColor.init(red: 0, green: 192, blue: 295, alpha: 1)
    return diskRenderer
}

override func viewDidLoad() {
    super.viewDidLoad()

    let coordinateRegion = MKCoordinateRegionMakeWithDistance(location, regionRadius, regionRadius)
    map.setRegion(coordinateRegion, animated: true)
    let diskOverlay: MKCircle = MKCircle.init(centerCoordinate: location, radius: 5000)
    map.addOverlay(diskOverlay)

    // Do any additional setup after loading the view.
}

我正在自学这些东西,如果我犯了一个明显的错误,请原谅我。

2 个答案:

答案 0 :(得分:4)

请参阅此问题的接受答案: How to create MKCircle in Swift?

步骤是:

  1. 确保此控制器实现MKMapViewDelegate

    class YourViewController: UIViewController, MKMapViewDelegate
    
  2. viewDidLoad中,将地图上的委托设置为self:

    override func viewDidLoad() {
    super.viewDidLoad()
    map.delegate = self;`
    
  3. 添加以下功能以渲染叠加层(更改颜色等):

    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    if let overlay = overlay as? MKCircle {
        let circleRenderer = MKCircleRenderer(circle: overlay)
        circleRenderer.fillColor = UIColor.blueColor()
        return circleRenderer
    }
    else {
       return MKOverlayRenderer(overlay: overlay)
    }
    } 
    
  4. 您的圆的半径太大,因为它当前已设置,整个地图将为蓝色。将它设置为小的,如1000,这样你就可以看到圆圈了。

答案 1 :(得分:0)

设置为mkmapviewdelegate的类中的objc:

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay
{
    if ([overlay isKindOfClass:[MKPolygon class]]) {
        MKPolygon *polygon = (MKPolygon *)overlay;
        MKPolygonRenderer *renderer = [[MKPolygonRenderer alloc] initWithPolygon:polygon];
        renderer.strokeColor = [UIColor blueColor];
        renderer.lineWidth = 5.;
        return renderer;
    }
    return [[MKOverlayRenderer alloc] initWithOverlay:overlay];
}