在MKMapView中计算MKPolygon的面积 [英] Calculate area of MKPolygon in an MKMapView
本文介绍了在MKMapView中计算MKPolygon的面积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是不知道如何计算MKMapView上的面积.解决这个问题的人了吗?
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的答案已在 Swift 5.0 中实现:
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.
}
这篇关于在MKMapView中计算MKPolygon的面积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文