Polyline not drawing from user location (blue dot)

好久不见. 提交于 2019-12-06 09:57:02

问题


- (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];
}

I am using this code to display polyline between to coordinates but i am getting this straight line. How to fix this issue.


回答1:


Based on your screenshot which shows the line not starting at the user location but apparently at some remote location to the east (probably 0,0 which is in the Atlantic Ocean off the coast of Africa)...

Your potential issue is that you are trying to read the userLocation coordinates in viewDidLoad but the map might not have obtained the location yet in which case you will be plotting from 0,0.

Make sure showsUserLocation is YES and read the userLocation and create the polyline in the didUpdateUserLocation delegate method instead.

Also remember that didUpdateUserLocation can be called multiple times if the device is moving or the OS gets a better location. This can cause multiple lines to be drawn (after you've moved the overlay creation there) if you don't account for it. You could remove existing overlays before adding a new one or just not add the overlay if it was already done.


In addition, please note the following:

The code posted tries to draw a line between two points but this:

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

allocates space for one point only.

Another issue is that it uses the size of CLLocationCoordinate2D instead of MKMapPoint which is what you are putting in the array (though this isn't technically creating a problem because those two structs happen to be the same size).

Try changing that line to:

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


Note that you can also just use the polylineWithCoordinates method so you don't have to convert the CLLocationCoordinate2Ds to MKMapPoints.




回答2:


Use MKDirections instead. tutorial is here



来源:https://stackoverflow.com/questions/20350685/polyline-not-drawing-from-user-location-blue-dot

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