- (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 坐标,但 map 可能尚未获取位置,在这种情况下,您将从 0,0 开始绘制。
确保 showsUserLocation
为 YES
并读取 userLocation 并在 didUpdateUserLocation
委托(delegate)方法中创建折线。
还请记住,如果设备正在移动或操作系统获得更好的位置,则可以多次调用 didUpdateUserLocation
。如果您不考虑这一点,这可能会导致绘制多条线(在您将覆盖创建移动到那里之后)。您可以在添加新叠加层之前删除现有叠加层,或者如果已经完成叠加层,则不添加叠加层。
此外,请注意以下事项:
发布的代码尝试在两个点之间画一条线,但是:
MKMapPoint *pointsArray = malloc(sizeof(CLLocationCoordinate2D));
仅为一个点分配空间。
另一个问题是它使用 CLLocationCooperative2D 的大小而不是您放入数组中的 MKMapPoint 的大小(尽管这在技术上不会产生问题,因为这两个结构体的大小恰好相同)。
尝试将该行更改为:
MKMapPoint *pointsArray = malloc(sizeof(MKMapPoint) * 2);
请注意,您也可以只使用 polylineWithCooperatives
方法,这样您就不必将 CLLocationCooperative2D 转换为 MKMapPoints。
关于ios - 折线未从用户位置绘制(蓝点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350685/