The polyline is not drawn from the user's location (blue dot)

- (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 use this code to display a polyline between coordinates, but I get this straight line. How to fix this problem.

enter image description here

+2
ios objective-c mapkit mkmapview mkpolyline
source share
2 answers

Depending on your screenshot, which shows that the line does not start with the user's location, but apparently in some remote location to the east (probably 0.0, which is located in the Atlantic Ocean off the coast of Africa) .. .

Your potential problem is that you are trying to read the userLocation coordinates in viewDidLoad , but the map may not have received the location, but in this case you will plot with 0.0.

Make sure that showsUserLocation is YES and read userLocation and create a polyline in the didUpdateUserLocation delegate didUpdateUserLocation .

Also remember that didUpdateUserLocation can be called multiple times if the device is moving or the OS is getting a better location. This can lead to drawing multiple lines (after you have moved the overlay creation) if you do not take it into account. You can delete existing overlays before adding a new one or simply not add an overlay if it has already been completed.


In addition, pay attention to the following:

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

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

Allocates space for only one point.

Another problem is that it uses the size of CLLocationCoordinate2D instead of MKMapPoint, which is what you put in the array (although this does not technically create a problem because the two structures are the same size).

Try changing this line to:

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


Note that you can also just use the polylineWithCoordinates method, so you do not need to convert CLLocationCoordinate2Ds to MKMapPoints.

+2
source share

Use MKDirections instead. the tutorial is here

0
source share

All Articles