在地图上的给定点之间绘制折线

时间:2012-08-16 09:45:09

标签: objective-c ios mapkit mkoverlay

我正在实现一个iOS应用程序,我想在地图上的几个给定坐标之间绘制一条折线。

我编写了代码,并从我的观点得到了折线,达到了无限的一点。换句话说,该行的起始点从我给定的纬度和长点开始,但该行的结尾是无限的,而不是另一个点。

这是我的代码......

我在名为NSMutableArray的{​​{1}}中填充坐标。阵列单元被填充一个用于纬度,一个用于经度。

routeLatitudes

并覆盖代表

MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * [routeLatitudes count]); 

for(int idx = 0; idx < [routeLatitudes count]; idx=idx+2)
{
    CLLocationCoordinate2D workingCoordinate;       
    workingCoordinate.latitude=[[routeLatitudes objectAtIndex:idx] doubleValue];
    workingCoordinate.longitude=[[routeLatitudes objectAtIndex:idx+1] doubleValue];  
    MKMapPoint point = MKMapPointForCoordinate(workingCoordinate);
    pointArr[idx] = point;      
}   

// create the polyline based on the array of points. 
routeLine = [MKPolyline polylineWithPoints:pointArr count:[routeLatitudes count]];
[mapView addOverlay:self.routeLine];
free(pointArr);

所以我需要在地图上的点之间绘制线条。该行的开头是第一个掉落的引脚,末端是最后一个掉落的引脚。

1 个答案:

答案 0 :(得分:4)

根据代码,routeLatitudes数组包含如下列出的对象:

  

索引0:点1的纬度
  指数1:点1的经度
  index 2:点2的纬度
  指数3:第2点的经度
  index 4:点3的纬度
  指数5:第3点的经度
  ...

因此,如果routeLatitudes.count为6,则实际上只有3分。

这意味着malloc分配了错误的点数,而polylineWithPoints调用也指定了覆盖的错误点数。

另一个问题是,由于pointArr只包含routeLatitudes所拥有的对象的一半,因此不能对两个数组使用相同的索引值。

for循环索引计数器idx在每次迭代时递增2,因为这是routeLatitudes点的布局方式,但是使用了相同的idx值设置pointArr

因此,idx=0设置pointArr[0],但idx=2设置pointArr[2],设置pointArr[1](而不是pointArr),依此类推。这意味着int pointCount = [routeLatitudes count] / 2; MKMapPoint* pointArr = malloc(sizeof(MKMapPoint) * pointCount); int pointArrIndex = 0; //it's simpler to keep a separate index for pointArr for (int idx = 0; idx < [routeLatitudes count]; idx=idx+2) { CLLocationCoordinate2D workingCoordinate; workingCoordinate.latitude=[[routeLatitudes objectAtIndex:idx] doubleValue]; workingCoordinate.longitude=[[routeLatitudes objectAtIndex:idx+1] doubleValue]; MKMapPoint point = MKMapPointForCoordinate(workingCoordinate); pointArr[pointArrIndex] = point; pointArrIndex++; } // create the polyline based on the array of points. routeLine = [MKPolyline polylineWithPoints:pointArr count:pointCount]; [mapView addOverlay:routeLine]; free(pointArr); 中的每个其他位置都保持未初始化状态,从而导致行“无限”。

因此更正的代码可能如下所示:

malloc

另请注意,在sizeof(CLLocationCoordinate2D)行中,我将sizeof(MKMapPoint)更正为sizeof(MKMapPoint)。这在技术上并没有引起问题,因为这两个结构恰好是相同的长度,但使用{{1}}是正确的,因为这是数组将包含的内容。

相关问题