Draw polyline between given points on the map

纵然是瞬间 提交于 2019-12-06 09:43:27

According to the code, the routeLatitudes array has objects listed like this:

index 0: latitude for point 1
index 1: longitude for point 1
index 2: latitude for point 2
index 3: longitude for point 2
index 4: latitude for point 3
index 5: longitude for point 3
...

So if routeLatitudes.count is 6, it actually has only 3 points.

This means the malloc is allocating the wrong number of points and the polylineWithPoints call is also specifying the wrong number of points for the overlay.

The other problem is that since pointArr will contain only half the objects that routeLatitudes has, you can't use the same index value for both arrays.

The for loop index counter idx is being incremented by 2 at each iteration because that's how the routeLatitudes points are layed out but then the same idx value is used to set pointArr.

So for idx=0, pointArr[0] is set but then for idx=2, pointArr[2] is set (instead of pointArr[1]), and so on. This means every other position in pointArr is left uninitialized resulting in the lines "going to infinity".

So the corrected code might look like this:

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); 

Also note in the malloc line, I corrected sizeof(CLLocationCoordinate2D) to sizeof(MKMapPoint). This technically wasn't causing a problem because those two structs happen to be the same length but it's correct to use sizeof(MKMapPoint) since that's what the array is going to contain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!