我有一个要求,其中有近数百个来自API的多边形数据,因此我必须在地图中快速绘制它们。
现在,要花费大量时间一次在地图上绘制50个多边形。因此,我在考虑一种将这些多边形聚类并且仅在捏到某个区域时才绘制/显示的方法。我只读过MKClusterAnnotation
,但从未听说过聚簇多边形。我还有其他方法可以优化图形多边形吗?
答案 0 :(得分:0)
不可能将MKPolygon
聚类,但是您可以使用MKPolygon-GPC库合并MKPolygon
。
以下使用此库的示例创建两个MKPolygon
对象的并集:
if let mergedPolygon = polygon1.fromUnion(with: polygon2) {
// Use the mergedPolygon
}
还可以检查两个多边形是否相交,在下面的示例中,它检查两个多边形是否相交,然后合并:
if polygon1.fromIntersection(with: polygon2) != nil, let mergedPolygon = polygon1.fromUnion(with: polygon2), merged.pointCount > 3 {
// Use the mergedPolygon
}
下面是MKPolygon
数组扩展,可用于合并多达MKPolygon
个:
extension Array where Element == MKPolygon {
var merged: [MKPolygon] {
guard self.count > 1 else { return self }
var count: Int!
var polygons = self
repeat {
count = polygons.count
} while self.merge(&polygons, indexes: (0..<count).map({ $0+1..<count }))
return polygons
}
private func merge(_ polygons: inout [MKPolygon], indexes: [Range<Int>]) -> Bool {
for (index, array) in indexes.enumerated() {
for i in array {
if polygons[index].fromIntersection(with: polygons[i]) != nil, let polygon = polygons[index].fromUnion(with: polygons[i]), polygon.pointCount > 3 {
polygons[index] = polygon
polygons.remove(at: i)
return true
}
}
}
return false
}
}
用法1 使用多边形数组[MKPolygon]
:
let result: [MKPolygon] = polygons.merged
用法2 使用坐标数组[[CLLocationCoordinate2D]]
:
let result: [MKPolygon] = coordinates.map({
MKPolygon(coordinates: $0, count: $0.count, interiorPolygons: nil)
}).merged