I just don't know how to calculate the area on the MKMapView. Anyone who has solved this problem yet?
This is my code, but it returns way too much:
func ringArea() -> Double{
var area: Double = 0
if templocations.count > 2 {
var p1,p2:CLLocationCoordinate2D
for var i = 0; i < templocations.count - 1; i++ {
var loc = templocations[i] as CLLocation
p1 = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)
loc = templocations[i+1] as CLLocation
p2 = CLLocationCoordinate2D(latitude: loc.coordinate.latitude, longitude: loc.coordinate.longitude)
var sinfunc: Float = (2 + sinf(Float(degreeToRadiant(p1.latitude))) + sinf(Float(degreeToRadiant(p2.latitude))))
area += degreeToRadiant(p2.longitude - p1.longitude) * Double(sinfunc)
}
area = area * kEarthRadius * kEarthRadius / 2;
}
return area
}
Stefan's answer implemented in Swift 5.0 :
import MapKit
let kEarthRadius = 6378137.0
func radians(degrees: Double) -> Double {
return degrees * .pi / 180
}
func regionArea(locations: [CLLocationCoordinate2D]) -> Double {
guard locations.count > 2 else { return 0 }
var area = 0.0
for i in 0..<locations.count {
let p1 = locations[i > 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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With