【发布时间】:2012-08-23 21:11:24
【问题描述】:
我正在尝试编写一个使用地图视图添加叠加层的应用程序。覆盖数据从文件加载到 NSArray 中,如下所示: ...
Revier355_2_Poly, //name of the polygon (string)
6, //no of coordinates of polygon (int)
47.4038673907557, //latitude of first coordinate (double)
8.5247885145479, //longitude of first coordinate (double)
47.4035082236459,
8.52436382148047,
47.4031174379495,
8.52493568571008,
47.403348653295,
8.52586444637587,
47.4037666977377,
8.52550468311683,
47.4038673907557,
8.5247885145479
...带有名称、点数、坐标的下一个多边形。
现在我想将上述数据转换成 MKPolygons 并将它们放在一个 NSDictionary 中。为此,我想创建包含文件中每个多边形坐标的 C 数组。这需要在运行时动态设置数组中的项目数。 这是我的问题:我无法做到这一点。你能帮忙或指出正确的方向吗?
这是我写的代码
int i = 0;
NSArray *data = [self loadDatafromFile];
NSMutableDictionary *overlays = [NSMutableDictionary new];
for ( i=0; i<data.count;i++)
{
if ([[data objectAtIndex: i] isKindOfClass: [NSString class]])
//start of new Polygon called Revier
{
//Name of Revier
NSString *polyName = (NSString*)[data objectAtIndex: i];
//PointCount is second entry after name
int noOfPoints = [[data objectAtIndex: (i+1)] intValue];
//Revier coordinates Error while setting Array size dynamically
CLLocationCoordinate2D *coord = malloc(sizeof(CLLocationCoordinate2D) * noOfPoints);
for (int j=0; j<noOfPoints+1; j+=2)
{
CLLocationCoordinate2D currCoord = CLLocationCoordinate2DMake([[data objectAtIndex:j+i] doubleValue],[[data objectAtIndex:j+i+1] doubleValue]);
coord[j] = currCoord;
}
MKPolygon *p = [MKPolygon polygonWithCoordinates:coord count:noOfPoints];
[overlays setObject: p forKey:polyName];
free(coord);
}
}
这是加载数据的代码...
- (NSArray *)loadDatafromFile
{
NSArray* myArr = [[NSArray alloc] initWithContentsOfFile:[self filePath]];
NSLog(@"%@",[self filePath]);
return myArr;
}
- (NSString *) filePath
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"polygone" ofType:@"txt"];
NSLog(@"%@",path);
return path;
}
【问题讨论】:
-
我也尝试像这样设置坐标的数组大小: CLLocation2DCoordinate coord[noOfPoints];但是,这也不起作用。
-
请添加
-loadDatafromFile的代码 -
你的txt文件真的是如图所示的格式吗? NSArray 的 initWithContentsOfFile 方法要求文件为 plist (xml) 格式。如果要按原样读取 txt 文件,则必须使用 NSString 的 stringWithContentsOfFile 方法,然后手动解析不可靠且不必要的工作的字符串。如果你把你的数据以 plist 格式,它会更容易读入一个字典数组,然后可以很容易地用来构造 MKPolygon 对象。
-
感谢您的提示。但是数据已经是 plist 格式了。我上面发布的是加载 plist 后 NSArray 的内容。但是,您能否提供更多关于如何使用字典构造 MKPolygons 的信息?
-
PS:这是我用来加载数据的 plist 开头的样子:ttp://www.apple.com/DTDs/PropertyList-1.0.dtd" rel="nofollow" target="_blank">apple.com/DTDs/PropertyList-1.0.dtd">
Revier1_Poly 204 47.22012717 8.808388347 47.2394585400515 8.79568994231076