Shmidt - 1 year ago 192
Objective-C Question

MKPolygon area calculation

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 algorithm: http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409.
It says:

Here is my code, which gave a wrong result (thousands times more than actual):

``````#define kEarthRadius 6378137
@implementation MKPolygon (AreaCalculation)
- (double) area {
double area = 0;
NSArray *coords = [self coordinates];
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];
}

}

return area;
}
- (NSArray *)coordinates {
NSMutableArray *points = [NSMutableArray arrayWithCapacity:self.pointCount];
for (int i = 0; i < self.pointCount; i++) {
MKMapPoint *point = &self.points[i];
}
return points.copy;
}

return radius * M_PI / 180;
}

@end
``````

What did I miss?

The final step for `i = N-1` and `i+1 = 0` (wrap around) is missing in your loop.