- (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.
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
isYES
and read the userLocation and create the polyline in thedidUpdateUserLocation
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:
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:
Note that you can also just use the
polylineWithCoordinates
method so you don't have to convert the CLLocationCoordinate2Ds to MKMapPoints.