Poles
Poles

Reputation: 3682

Is it possible to cluster MKPolygon on mapView in ios

I have a requirement where there are nearly hundreds of polygon data coming from API and I have to draw them quickly in the map.

Right now it is taking a significant time to draw 50 polygons on map at a time. So I am thinking a way to cluster those polygons & only draw/show when I pinch in to a region. I only read about MKClusterAnnotation but never heard about clustering polygon. Is there any other way I can optimize drawing polygon?

Upvotes: 2

Views: 362

Answers (1)

AamirR
AamirR

Reputation: 12198

Its not possible to cluster MKPolygons, but you can merge MKPolygons using the MKPolygon-GPC library.

Example below using this library creates a union of two MKPolygon objects:

if let mergedPolygon = polygon1.fromUnion(with: polygon2) {
    // Use the mergedPolygon
}

It is also possible to check if two polygons are intersecting, in example below it checks if 2 polygons are intersecting, then it merges:

if polygon1.fromIntersection(with: polygon2) != nil, let mergedPolygon = polygon1.fromUnion(with: polygon2), merged.pointCount > 3 {
    // Use the mergedPolygon
}

Below is a MKPolygon Array extension that you can use to merge as many MKPolygons:

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
    }

}

Usage-1 uses polygons array [MKPolygon]:

let result: [MKPolygon] = polygons.merged

Usage-2 uses coordinates array [[CLLocationCoordinate2D]]:

let result: [MKPolygon] = coordinates.map({
    MKPolygon(coordinates: $0, count: $0.count, interiorPolygons: nil)
}).merged

Upvotes: 0

Related Questions