如何在iOS中獲取MKPolygon或MKOverlay的區域?如何在iOS中獲取MKPolygon的區域
我已經能夠分解成三角形的多邊形,並做一些數學來獲得該地區。但是,對於不規則的多邊形不適用。
我在想這樣做有點像「一個更復雜的情況下,」在這裏:http://www.mathopenref.com/coordpolygonarea2.html
我一直希望有一個與MapKit一個簡單的解決方案。
感謝, 添
如何在iOS中獲取MKPolygon或MKOverlay的區域?如何在iOS中獲取MKPolygon的區域
我已經能夠分解成三角形的多邊形,並做一些數學來獲得該地區。但是,對於不規則的多邊形不適用。
我在想這樣做有點像「一個更復雜的情況下,」在這裏:http://www.mathopenref.com/coordpolygonarea2.html
我一直希望有一個與MapKit一個簡單的解決方案。
感謝, 添
我想通了這一點通過多邊形中的點做一個小圈。每3分,我檢查一下這個三角形的中心是否在多邊形中。如果它繼續,如果沒有,則連接多邊形,以便多邊形中沒有凹陷。完成後,獲取多邊形中的三角形並進行數學計算以獲取該區域。然後減去刪除的三角形。
希望這可以幫助別人。
下面是我使用的實現。
#define kEarthRadius 6378137
@implementation MKPolygon (AreaCalculation)
- (double) area {
double area = 0;
NSMutableArray *coords = [[self coordinates] mutableCopy];
[coords addObject:[coords firstObject]];
if (coords.count > 2) {
CLLocationCoordinate2D p1, p2;
for (int i = 0; i < coords.count - 1; i++) {
p1 = [coords[i] MKCoordinateValue];
p2 = [coords[i + 1] MKCoordinateValue];
area += degreesToRadians(p2.longitude - p1.longitude) * (2 + sinf(degreesToRadians(p1.latitude)) + sinf(degreesToRadians(p2.latitude)));
}
area = - (area * kEarthRadius * kEarthRadius/2);
}
return area;
}
- (NSArray *)coordinates {
NSMutableArray *points = [NSMutableArray arrayWithCapacity:self.pointCount];
for (int i = 0; i < self.pointCount; i++) {
MKMapPoint *point = &self.points[i];
[points addObject:[NSValue valueWithMKCoordinate:MKCoordinateForMapPoint(* point)]];
}
return points.copy;
}
double degreesToRadians(double radius) {
return radius * M_PI/180;
}
在斯威夫特3:
let kEarthRadius = 6378137.0
extension MKPolygon {
func degreesToRadians(_ radius: Double) -> Double {
return radius * .pi/180.0
}
func area() -> Double {
var area: Double = 0
var coords = self.coordinates()
coords.append(coords.first!)
if (coords.count > 2) {
var p1: CLLocationCoordinate2D, p2: CLLocationCoordinate2D
for i in 0..<coords.count-1 {
p1 = coords[i]
p2 = coords[i+1]
area += degreesToRadians(p2.longitude - p1.longitude) * (2 + sin(degreesToRadians(p1.latitude)) + sin(degreesToRadians(p2.latitude)))
}
area = abs(area * kEarthRadius * kEarthRadius/2)
}
return area
}
func coordinates() -> [CLLocationCoordinate2D] {
var points: [CLLocationCoordinate2D] = []
for i in 0..<self.pointCount {
let point = self.points()[i]
points.append(MKCoordinateForMapPoint(point))
}
return Array(points)
}
}
可能是巨大的,如果你能在這裏分享代碼。 – Shmidt 2014-02-19 09:00:34
請分享代碼,如果你已經完成。 – ravinder521986 2014-07-09 08:18:23