Polyline not drawing from user location (blue dot)

1.3k views Asked by At
- (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.

enter image description here

2

There are 2 answers

3
AudioBubble On BEST ANSWER

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.

1
Slashik On

Use MKDirections instead. tutorial is here