ios - MKMapKit 可拖动注释和绘制多边形

标签 ios swift mkmapview

我目前正在尝试让用户向 map 添加图钉,然后 map 将绘制一个连接这些图钉的多边形。但是我想扩展它以允许用户能够拖动图钉并且多边形将相应地更新。 MKMapView 根据它们在数组中的排列(如果我没记错的话)从坐标数组中绘制多边形。我现在面临的问题是如何在用户重新定位引脚后更新多边形。

var touchCoordinatesWithOrder: [(coordinate: CLLocationCoordinate2D, order: Int)] = []
var counter = 0

func addLongPressGesture() {
    let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
    longPressRecogniser.minimumPressDuration = 1.0
    mapView.addGestureRecognizer(longPressRecogniser)

}

func handleLongPress(gestureRecognizer: UIGestureRecognizer) {
    if gestureRecognizer.state != .Began {
        return
    }

    let touchPoint = gestureRecognizer.locationInView(self.mapView)
    let touchMapCoordinate = mapView.convertPoint(touchPoint, toCoordinateFromView: mapView)

    let annotation = MKPointAnnotation()
    annotation.coordinate = touchMapCoordinate
    mapView.addAnnotation(annotation)

    touchCoordinatesWithOrder.append((coordinate: touchMapCoordinate, order: counter))
    counter += 1

}


@IBAction func drawAction(sender: AnyObject) {
    if touchCoordinatesWithOrder.count <= 2 {
        print("Not enough coordinates")
        return
    }

    var coords = [CLLocationCoordinate2D]()
    for i in 0..<touchCoordinatesWithOrder.count {
        coords.append(touchCoordinatesWithOrder[i].coordinate)
    }

    let polygon = MKPolygon(coordinates: &coords, count: coords.count)
    mapView.addOverlay(polygon)
    counter = 0
}

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
    // if the user repositioned pin number2 then how to I update my array?
}

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKPolygon {
        let polygonView = MKPolygonRenderer(overlay: overlay)
        polygonView.strokeColor = UIColor.blackColor()
        polygonView.lineWidth = 0.5
        return polygonView
    }
    return MKPolylineRenderer()
}

最佳答案

要使引脚可拖动,您需要在 MKAnnotationView 上设置 draggable = true。实现 viewForAnnotation 并出队或创建注释,然后设置 draggable = true。确保设置了 MKMapView 委托(delegate),否则将不会调用任何委托(delegate)方法。

您可能还会发现将注释存储在数组中比仅存储坐标更容易。 map View 保留对数组中注释的引用,因此当点在 map 中移动时,注释会自动更新。

您的问题没有说明您是否需要绘制一条路径围绕这些点,或者通过这些点。如果要绘制围绕点的叠加层,则还需要计算坐标的凸包。代码示例执行此操作,尽管它很容易删除。

例子:

class MapAnnotationsOverlayViewController: UIViewController, MKMapViewDelegate {

    @IBOutlet var mapView: MKMapView!

    // Array of annotations - modified when the points are changed.
    var annotations = [MKPointAnnotation]()

    // Current polygon displayed in the overlay.
    var polygon: MKPolygon?

    override func viewDidLoad() {
        super.viewDidLoad()
        mapView.delegate = self    
        addLongPressGesture()
    }

    func addLongPressGesture() {
        let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
        longPressRecogniser.minimumPressDuration = 0.25
        mapView.addGestureRecognizer(longPressRecogniser)

    }

    func handleLongPress(gestureRecognizer: UIGestureRecognizer) {

        guard gestureRecognizer.state == .Began else {
            return
        }

        let touchPoint = gestureRecognizer.locationInView(self.mapView)
        let touchMapCoordinate = mapView.convertPoint(touchPoint, toCoordinateFromView: mapView)


        let annotation = MKPointAnnotation()

        // The annotation must have a title in order for it to be selectable.
        // Without a title the annotation is not selectable, and therefore not draggable.
        annotation.title = "Point \(annotations.count)"
        annotation.coordinate = touchMapCoordinate
        mapView.addAnnotation(annotation)

        // Add the new annotation to the list.
        annotations.append(annotation)

        // Redraw the overlay.
        updateOverlay()
    }

    @IBAction func drawAction(sender: AnyObject) {
        updateOverlay()
    }

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

        var view = mapView.dequeueReusableAnnotationViewWithIdentifier("pin")

        if let view = view {
            view.annotation = annotation
        }
        else {
            view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "pin")

            // Allow the pin to be repositioned.
            view?.draggable = true
        }

        return view
    }

    func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {

    // The map view retains a reference to the same annotations in the array.
    // The annotation in the array is automatically updated when the pin is moved.

        updateOverlay()
    }

    func updateOverlay() {

        // Remove existing overlay.
        if let polygon = self.polygon {
            mapView.removeOverlay(polygon)
        }

        self.polygon = nil

        if annotations.count < 3 {
            print("Not enough coordinates")
            return
        }

        // Create coordinates for new overlay.
        let coordinates = annotations.map({ $0.coordinate })

        // Sort the coordinates to create a path surrounding the points.
        // Remove this if you only want to draw lines between the points.
        var hull = sortConvex(coordinates)

        let polygon = MKPolygon(coordinates: &hull, count: hull.count)
        mapView.addOverlay(polygon)

        self.polygon = polygon
    }

    func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {
        if overlay is MKPolygon {
            let polygonView = MKPolygonRenderer(overlay: overlay)
            polygonView.strokeColor = UIColor.blackColor()
            polygonView.lineWidth = 0.5
            return polygonView
        }
        return MKPolylineRenderer()
    }
}

这是凸包排序算法(改编自 Gist on GitHub )。

func sortConvex(input: [CLLocationCoordinate2D]) -> [CLLocationCoordinate2D] {

    // X = longitude
    // Y = latitude

    // 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
    // Returns a positive value, if OAB makes a counter-clockwise turn,
    // negative for clockwise turn, and zero if the points are collinear.
    func cross(P: CLLocationCoordinate2D, _ A: CLLocationCoordinate2D, _ B: CLLocationCoordinate2D) -> Double {
        let part1 = (A.longitude - P.longitude) * (B.latitude - P.latitude)
        let part2 = (A.latitude - P.latitude) * (B.longitude - P.longitude)
        return part1 - part2;
    }

    // Sort points lexicographically
    let points = input.sort() {
        $0.longitude == $1.longitude ? $0.latitude < $1.latitude : $0.longitude < $1.longitude
    }

    // Build the lower hull
    var lower: [CLLocationCoordinate2D] = []
    for p in points {
        while lower.count >= 2 && cross(lower[lower.count-2], lower[lower.count-1], p) <= 0 {
            lower.removeLast()
        }
        lower.append(p)
    }

    // Build upper hull
    var upper: [CLLocationCoordinate2D] = []
    for p in points.reverse() {
        while upper.count >= 2 && cross(upper[upper.count-2], upper[upper.count-1], p) <= 0 {
            upper.removeLast()
        }
        upper.append(p)
    }

    // Last point of upper list is omitted because it is repeated at the
    // beginning of the lower list.
    upper.removeLast()

    // Concatenation of the lower and upper hulls gives the convex hull.
    return (upper + lower)
}

这是凸包排序的样子(围绕点绘制的路径):

Convex hull surrounding points

这是没有排序的样子(按顺序从一个点到另一个点绘制的路径):

Point-to-point path

关于ios - MKMapKit 可拖动注释和绘制多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38344993/

相关文章:

ios - 以 NSIntegers 作为参数返回一个 NSNumbers 数组

ios - MKAnnotationView 正在失去对 MKAnnotation 的引用

objective-c - Swift 模块不使用 L10N 中的本地化内容

ios - 如何使用 Swift 在饼图中正确设置 xValuePosition 和 yValuePosition?

iPhone:MKAnnotation 显示弹出窗口?

ios - 快速向 callOut View 添加标题

ios - 使用按钮执行一段代码几秒/分钟?

ios - 如何在 iOS 中以编程方式清除 .log 文件的内容

iphone - 不需要的变量释放(iOS)

ios - 如何在 SwiftUI 中更改步进器的背景颜色?