0
votes

I am working on a project where I need to draw a line on map with each update of user location to show a full route where user has travelled.

I am currently using Mapbox iOS SDK (v4.0.2) for this. To achieve above goal I am using MGLPolyline to draw a line over map.

With the following code provided, I am facing an issue as some default shape automatically get drawn before the route gets started.

Following is the code which I have implemented in my project :

@interface ViewController () <MGLMapViewDelegate>
{
    MGLPolyline *polyline;
}
@end


- (void)mapView:(MGLMapView *)mapView didUpdateUserLocation:(MGLUserLocation *)userLocation
{
    CLLocationCoordinate2D coord[1];
    coord[0] = userLocation.coordinate;

    if (polyline)
    {
        [polyline appendCoordinates:coord count:sizeof(coord)];
    }
    else
    {
        polyline = [MGLPolyline polylineWithCoordinates:coord count:sizeof(coord)];
        __weak typeof(self) weakSelf = self;
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [weakSelf.mapView addAnnotation:polyline];
        });
    }
}
- (CGFloat)mapView:(MGLMapView *)mapView alphaForShapeAnnotation:(MGLShape *)annotation
{
    return 1.0f;
}

- (CGFloat)mapView:(MGLMapView *)mapView lineWidthForPolylineAnnotation:(MGLPolyline *)annotation
{
    return 5.0f;
}

- (UIColor *)mapView:(MGLMapView *)mapView strokeColorForShapeAnnotation:(MGLShape *)annotation
{
    return [UIColor redColor];
}

1

1 Answers

0
votes

i've done similar project before with swift.

user selects two point on map for beginning and destination then we use a google service which takes two point and gives list of point for best route and i was using this method to draw a polyLine

i think you have two way to do this

1_using didupdate func of mapkit for saving all point that user moves then use the func i put below for drawing poly line

2_take the beginning and destination points then draw a polyline

  func addPolyLineToMap(googlemaplist: [CLLocation?]){


    var coordinates = googlemaplist.map({ (location: CLLocation!) -> CLLocationCoordinate2D in
        return location.coordinate
    })

    print("locatios count")
    print(googlemaplist.count)

    var polyline = MKPolyline(coordinates: &coordinates, count: googlemaplist.count)

    DispatchQueue.main.async {
        self.MapKit.add(polyline)

    }
}