获取注释的边界

时间:2018-03-13 06:35:50

标签: ios swift mapkit mkmapview

我正在尝试找到我MapView上的注释列表的界限。

我在javascript中看到你可以将注释添加到图层的FeatureGroup,然后获取该组的边界。

但是,我无法在Swift SDK中找到它。我怎样才能获得一组注释的界限?

2 个答案:

答案 0 :(得分:0)

您需要使用.annotations的{​​{1}}属性,并获得 minX minY maxX maxY ,之后您可以将这些点作为坐标返回并添加叠加层(如果需要)

MKMapView

完整示例代码

func getCordinatesOfRectAnnotations(annotationsArray:[MKAnnotation]) ->[CLLocationCoordinate2D]{
    let minX : Double = annotationsArray.map({MKMapPointForCoordinate($0.coordinate).x}).min()!
    let minY : Double = annotationsArray.map({MKMapPointForCoordinate($0.coordinate).y}).min()!
    let maxX : Double = annotationsArray.map({MKMapPointForCoordinate($0.coordinate).x}).max()!
    let maxY : Double = annotationsArray.map({MKMapPointForCoordinate($0.coordinate).y}).max()!

    var result : [CLLocationCoordinate2D] = []
    result.append(MKCoordinateForMapPoint(MKMapPoint(x: minX, y: minY)))
    result.append(MKCoordinateForMapPoint(MKMapPoint(x: maxX, y: minY)))
    result.append(MKCoordinateForMapPoint(MKMapPoint(x: maxX, y: maxY)))
    result.append(MKCoordinateForMapPoint(MKMapPoint(x: minX, y: maxY)))
    return result
}

<强>结果

enter image description here

答案 1 :(得分:0)

此功能未在MapKit SDK中进行编码,但是获取任何边界框坐标或您的需求非常简单,例如:

1)使用坐标数组查找边界框的SouthWest和NorthEast:

let x = coordinates.map({MKMapPointForCoordinate($0).x})
let y = coordinates.map({MKMapPointForCoordinate($0).y})

let min_OR_southWest = MKCoordinateForMapPoint(MKMapPoint(x: x.min()!, y: y.max()!))
let max_OR_northEast = MKCoordinateForMapPoint(MKMapPoint(x: x.max()!, y: y.min()!))

这将为您提供以下标记为红色的坐标

enter image description here

如果需要上图中其他点的坐标,则 just 使用xy上方的2个变量,例如,如果您需要nw坐标:

let nwCoordinate = MKCoordinateForMapPoint(MKMapPoint(x: x.min()!, y: y.min()!))

2)提供使用MKPolygon的另一个示例,该示例也可以用于MKPolyline覆盖

extension MKPolygon {
    var boundingBox: [CLLocationCoordinate2D] {
        var coords = [CLLocationCoordinate2D](repeating: kCLLocationCoordinate2DInvalid, count: self.pointCount)
        self.getCoordinates(&coords, range: NSMakeRange(0, self.pointCount))

        let x = coords.map({MKMapPointForCoordinate($0).x})
        let y = coords.map({MKMapPointForCoordinate($0).y})
        let min = MKCoordinateForMapPoint(MKMapPoint(x: x.min()!, y: y.max()!))
        let max = MKCoordinateForMapPoint(MKMapPoint(x: x.max()!, y: y.min()!))
        return [min.latitude, max.latitude, min.longitude, max.longitude]
    }
}