Personally, I'd be inclined to do it as follows:
First, I'd be inclined to save the C array of
CLLocationCoordinate2D
coordinates that I pass toMKPolygon
instance methodpolygonWithCoordinates
(rather than aMKMapPoint
C array). You can adapt this code if you'd rather useMKMapPoints
, but I prefer a format which I can examine externally and make sense of (namely the latitude and longitude values ofCLLocationCoordinate2D
). So, let's assume that you make yourMKPolygon
with a line of code like so:MKPolygon* poly = [MKPolygon polygonWithCoordinates:coordinates count:count];
You could, therefore save the coordinates like so:
[self writeCoordinates:coordinates count:count file:filename];
Where
writeCoordinates:count:filename:
is defined as follows:- (void)writeCoordinates:(CLLocationCoordinate2D *)coordinates count:(NSUInteger)count file:(NSString *)filename { NSData *data = [NSData dataWithBytes:coordinates length:count * sizeof(CLLocationCoordinate2D)]; [data writeToFile:filename atomically:NO]; }
You could then make the
MKPolygon
from the file with:MKPolygon* poly = [self polygonWithContentsOfFile:filename];
where
polygonWithContentsOfFile
is defined as:- (MKPolygon *)polygonWithContentsOfFile:(NSString *)filename { NSData *data = [NSData dataWithContentsOfFile:filename]; NSUInteger count = data.length / sizeof(CLLocationCoordinate2D); CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)data.bytes; return [MKPolygon polygonWithCoordinates:coordinates count:count]; }
Alternatively, you could read and write the array of
CLLocationCoordinate2D
in a plist format (which renders it in a human readable format), by replacing the two above methods with:const NSString *kLatitudeKey = @"latitude"; const NSString *kLongitudeKey = @"longitude"; - (void)writeCoordinates:(CLLocationCoordinate2D *)coordinates count:(NSUInteger)count file:(NSString *)filename { NSMutableArray *array = [NSMutableArray arrayWithCapacity:count]; for (NSUInteger i = 0; i < count; i++) { CLLocationCoordinate2D coordinate = coordinates[i]; [array addObject:@{kLatitudeKey:@(coordinate.latitude), kLongitudeKey:@(coordinate.longitude)}]; } [array writeToFile:filename atomically:NO]; } - (MKPolygon *)polygonWithContentsOfFile:(NSString *)filename { NSArray *array = [NSArray arrayWithContentsOfFile:filename]; NSUInteger count = [array count]; CLLocationCoordinate2D coordinates[count]; for (NSUInteger i = 0; i < count; i++) { NSDictionary *dictionary = array[i]; coordinates[i].latitude = [dictionary[kLatitudeKey] doubleValue]; coordinates[i].longitude = [dictionary[kLongitudeKey] doubleValue]; } return [MKPolygon polygonWithCoordinates:coordinates count:count]; }
Clearly you'd want to add error checking code to make sure that the writeToFile
and the dataWithContentsOfFile
(or arrayWithContentsOfFile
) succeeded, but hopefully this gives you the idea.