如何使用MapKit并迅速绘制多边形叠加

问题描述 投票:6回答:1

我试图让下面的代码在地图上绘制多边形,但由于某种原因,这是行不通的。我怎么去错在这里?

import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let initialLocation = CLLocation(latitude: 49.140838, longitude: -123.127886)
        centerMapOnLocation(initialLocation)
        addBoundry()
    }


    func addBoundry()
    {
        var points=[CLLocationCoordinate2DMake(49.142677,  -123.135139),CLLocationCoordinate2DMake(49.142730, -123.125794),CLLocationCoordinate2DMake(49.140874, -123.125805),CLLocationCoordinate2DMake(49.140885, -123.135214)]

        let polygon = MKPolygon(coordinates: &points, count: points.count)

        mapView.addOverlay(polygon)
    }


    let regionRadius: CLLocationDistance = 1000
    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
            regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordinateRegion, animated: true)
    }


}


func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKPolygon {
        let polygonView = MKPolygonRenderer(overlay: overlay)
        polygonView.strokeColor = UIColor.magentaColor()

        return polygonView
    }

    return nil
}
ios swift mapkit point-in-polygon
1个回答
5
投票

这样看来,你已经实现mapView(_:renderFor:)(以前称为rendererForOverlay)作为一个全球性的功能。该方法必须是ViewController类定义,或者甚至更好,内保持我们的代码很好的组织,一个MKMapViewDelegate扩展中:

extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        ...
    }
}

此外,请确保您已经定义了视图控制器是地图视图的delegate。这可能是最容易做的是,在IB,但你也可以做到这一点在viewDidLoad

mapView.delegate = self
© www.soinside.com 2019 - 2024. All rights reserved.