gpt4 book ai didi

ios - 如何在iOS中获取MKPolygon的区域

转载 作者:行者123 更新时间:2023-12-01 19:12:06 24 4
gpt4 key购买 nike

如何在iOS中获取MKPolygon或MKOverlay的区域?

我已经能够将“多边形”分解为三角形,并进行一些数学运算以获得面积。但是,不适用于不规则多边形。

我当时正在考虑做类似“更复杂的案例”的事情:http://www.mathopenref.com/coordpolygonarea2.html

我希望MapKit有一个更简单的解决方案。

谢谢,
提姆

最佳答案

polygon on a sphere area 1
polygon on a sphere area 2

这是我正在使用的实现。

#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;
}

在Swift 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)
}
}

关于ios - 如何在iOS中获取MKPolygon的区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15880785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com