MKPolygon area calculation

前端 未结 3 1015
萌比男神i
萌比男神i 2020-12-01 17:39

I\'m trying to make an area calculation category for MKPolygon. I found some JS code https://github.com/mapbox/geojson-area/blob/master/index.js#L1 with a link to the algori

3条回答
  •  鱼传尺愫
    2020-12-01 18:08

    The whole algorithm implemented in Swift 3.0 :

    import MapKit
    let kEarthRadius = 6378137.0
    
    // CLLocationCoordinate2D uses degrees but we need radians
    func radians(degrees: Double) -> Double {
        return degrees * M_PI / 180;
    }
    
    func regionArea(locations: [CLLocationCoordinate2D]) -> Double {
    
        guard locations.count > 2 else { return 0 }
        var area = 0.0
    
        for i in 0.. 0 ? i - 1 : locations.count - 1]
            let p2 = locations[i]
    
            area += radians(degrees: p2.longitude - p1.longitude) * (2 + sin(radians(degrees: p1.latitude)) + sin(radians(degrees: p2.latitude)) )
        }
    
        area = -(area * kEarthRadius * kEarthRadius / 2);
    
        return max(area, -area) // In order not to worry about is polygon clockwise or counterclockwise defined.
    }
    

提交回复
热议问题