折线不从用户位置绘制(蓝点)

- (void)viewDidLoad { [super viewDidLoad]; CLLocationCoordinate2D currentLocation; currentLocation.latitude = self.mapView.userLocation.location.coordinate.latitude; currentLocation.longitude = self.mapView.userLocation.location.coordinate.longitude; CLLocationCoordinate2D otherLocation; otherLocation.latitude = [lati doubleValue]; otherLocation.longitude = [longi doubleValue]; MKPointAnnotation *mka = [[MKPointAnnotation alloc]init]; mka.Coordinate = otherLocation; mka.title = @"!"; [self.mapView addAnnotation:mka]; self.mapView.delegate = self; MKMapPoint *pointsArray = malloc(sizeof(CLLocationCoordinate2D)); pointsArray[0]= MKMapPointForCoordinate(currentLocation); pointsArray[1]= MKMapPointForCoordinate(otherLocation); routeLine = [MKPolyline polylineWithPoints:pointsArray count:2]; free(pointsArray); [self.mapView addOverlay:routeLine]; } 

我正在使用此代码显示坐标之间的折线,但我得到这条直线。 如何解决这个问题。

在这里输入图像说明

根据你的屏幕截图显示,这条线不是从用户位置开始的,而是显然是在东边的一些偏远的地方(可能是0,0,位于非洲沿海的大西洋)。

您的潜在问题是,您正尝试读取viewDidLoad的userLocation坐标,但是地图可能尚未获取位置,在这种情况下,您将从0,0进行绘图。

确保showsUserLocationYES然后读取userLocation,然后在didUpdateUserLocation委托方法中创build多段线。

另外请记住,如果设备正在移动或操作系统获得更好的位置, didUpdateUserLocation可以多次调用didUpdateUserLocation 。 这可能会导致多行(如果您没有考虑它,您已经移动覆盖层创build后)绘制。 在添加新的叠加层之前,您可以删除现有的叠加层,或者如果叠加层已经完成,则不要添加叠加层。


另外请注意以下几点:

发布的代码尝试绘制两点之间的一条线,但是:

 MKMapPoint *pointsArray = malloc(sizeof(CLLocationCoordinate2D)); 

只分配一个点的空间。

另一个问题是,它使用CLLocationCoordinate2D的大小,而不是MKMapPoint,这就是你在数组中放置的数据(虽然这在技术上并不会造成问题,因为这两个结构恰好是相同的大小)。

尝试将该行更改为:

 MKMapPoint *pointsArray = malloc(sizeof(MKMapPoint) * 2); 

请注意,您也可以使用polylineWithCoordinates方法,因此您不必将CLLocationCoordinate2Ds转换为MKMapPoints。

改用MKDirections。 教程在这里