MKPolyline not showing on MKMapView - ios

Here's the code. Its pretty straight forward. I'm making a path for someone who is walking.
So, here's the code for my ViewController.m file :
#import "ViewController.h"
#interface ViewController ()
#property BOOL firstTime;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.mapView setDelegate:self];
[self.mapView setShowsUserLocation:YES];
[self.mapView setMapType:MKMapTypeHybrid];
[self setLocationManager:[[CLLocationManager alloc] init]];
[self.locationManager setDelegate:self];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager startUpdatingLocation];
self.index = 0;
self.firstTime = YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
if(self.firstTime)
{
CLLocation *startingLocation = [locations objectAtIndex:0];
self.startingPointCooridinates = startingLocation.coordinate;
self.index++;
MKPointAnnotation *startingPointAnnotation = [[MKPointAnnotation alloc] init];
startingPointAnnotation.title = #"Starting Point";
startingPointAnnotation.coordinate = startingLocation.coordinate;
[self.mapView addAnnotation:startingPointAnnotation];
self.firstTime = false;
}
[self.locations addObject:[locations objectAtIndex:0]];
CLLocationCoordinate2D coordinates[[self.locations count]];
for(int i = 0; i < self.locations.count; i++)
{
CLLocation *currentLocation = [locations objectAtIndex:i];
coordinates[i] = currentLocation.coordinate;
}
MKPolyline *pathPolyline = [MKPolyline polylineWithCoordinates:coordinates count:self.locations.count];
[self.mapView addOverlay:pathPolyline];
}
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
if([overlay isKindOfClass:[MKPolyline class]])
{
MKPolylineRenderer *polylineRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
polylineRenderer.fillColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
polylineRenderer.strokeColor = [[UIColor redColor] colorWithAlphaComponent:0.7];
polylineRenderer.lineWidth = 2.0;
return polylineRenderer;
}
else
{
return nil;
}
}
Now, only the annotation is showing and there isn't any MKPolyline showing up. What am I doing wrong ? Thanks.

As mentioned in the comments, your locations array is never allocated and initialized so it's nil and calls to it (like addObject) do nothing and so the polyline never gets any coordinates added to it (and so it doesn't show).
In viewDidLoad, before starting the CLLocationManager, alloc and init the array:
self.locations = [NSMutableArray array];
Another issue you will encounter is with this line in didUpdateLocations in the for loop:
CLLocation *currentLocation = [locations objectAtIndex:i];
Here, locations (without the self.) refers to the delegate method's local parameter variable and not your locations class-instance-level property variable. The compiler must be warning you about this with a message like "Local declaration of 'locations' hides instance variable".
In this case, the warning is critical. What you really mean to do here is reference the locations property variable where you are storing the user's complete trail of coordinates and not the local variable which only has the last x un-reported locations (usually only 1 object).
So that line should be changed to:
CLLocation *currentLocation = [self.locations objectAtIndex:i];
It would be better if you just used a different name than locations to avoid these problems.
As also mentioned in the comments, since you are adding an overlay with the user's complete trail of motion every time the user moves, you need to remove the previous overlay first. Otherwise, you will needlessly be adding multiple overlays to the map since the last overlay covers the entire motion. The previous overlays are not obviously visible since they have the same coordinates, the same color, and the same line width. So before calling addOverlay, the simplest thing to do is call removeOverlays with map's current list of overlays:
//remove any previous overlays first...
[self.mapView removeOverlays:mapView.overlays];
//now add overlay with the updated trail...
[self.mapView addOverlay:pathPolyline];
A minor point not affecting the display is that setting fillColor for a polyline has no effect. You only need to set strokeColor which the code is doing. You can remove the call to set fillColor.
Finally, you may be interested in seeing Apple's Breadcrumb sample app. Their version uses a custom overlay which can be dynamically updated without having to remove and add overlays every time there's a change or addition.

Related

Why This Code Does Not Draw Polyline on MKMapView

I have the following code, with which i am trying to draw a polyline between a set of coordinates (which are correct as I also use them to add pins to the map, and those work fine).
I call a drawing method to initiate the drawing like so (the array in the method call contains the necessary coordinates):
[self drawRoute:[[transportData objectForKey:#"19"] objectForKey:#"stops"]];
This is the actual method that is supposed to draw the line on the map (selectedRoute is an MKPolyline object):
- (void)drawRoute:(NSArray *)routePointsArray {
if (selectedRoute) {
[mapView removeOverlay:selectedRoute];
selectedRoute = nil;
}
CLLocationCoordinate2D routeCoordinates[routePointsArray.count];
for (int i = 0; i < routePointsArray.count; i++) {
float latitude = [[[routePointsArray objectAtIndex:i] objectForKey:#"lat"] floatValue];
float longitude = [[[routePointsArray objectAtIndex:i] objectForKey:#"lon"] floatValue];
CLLocationCoordinate2D routePoint = CLLocationCoordinate2DMake(latitude, longitude);
routeCoordinates[i] = routePoint;
}
selectedRoute = [MKPolyline polylineWithCoordinates:routeCoordinates count:routePointsArray.count];
[mapView addOverlay:selectedRoute];
[mapView setVisibleMapRect:[selectedRoute boundingMapRect]];
}
And this is my delegate:
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
MKPolylineRenderer *routeLineView = [[MKPolylineRenderer alloc] initWithPolyline:selectedRoute];
if(overlay == selectedRoute)
{
if(nil == routeLineView)
{
routeLineView = [[MKPolylineRenderer alloc] initWithPolyline:selectedRoute];
routeLineView.fillColor = [UIColor redColor];
routeLineView.strokeColor = [UIColor redColor];
routeLineView.lineWidth = 5;
}
return routeLineView;
}
return nil;
}
I kind of narrowed it down to the routeCoordinates array not getting filled up with coordinates, but I do not understand why.
Also, if you spot any mistakes in the code I would really appreciate if you could point those out to me (possibly with a solution) as I am just learning this part of iOS and can use any help I can get.
You have an error in your rendererForOverlay method.
The first thing it does is assign an instance of MKPolylineRenderer to routeLineView, but later you only actually add the overlay if routeLineView is nil, which it won't be.
Remove the line that assigns the initial value to routeLineView.

MapBox. layerForAnnotation not being called. Drawing shape

I am trying to draw a path for the user from point A to point B with given coordinates.
LayerForAnnotation isn't being called after I add the annotation. I am new to using MapBox SDK and don't really know what I'm doing wrong. I looked for instructions on adding Shapes on the MapBox documentation. I tried changing to RMPointAnnotation but did not work and isn't supposed to according to this: Issue GitHub RMAnnotation.
I have checked if there is any info about the implementation of this delegate but haven't found a lot on the MapBox documentation page. I downloaded the example project that illustrates annotations from here: Weekend Picks sample.
This is the code I am using:
- (void) makeRoutingAnnotations
{
// Translate updated path with new coordinates.
NSInteger numberOfSteps = _path.count;
NSMutableArray *coordinates = [[NSMutableArray alloc] init];
for (NSInteger index = 0; index < numberOfSteps; ++index) {
CLLocation *location = [_path objectAtIndex:index];
[coordinates addObject:location];
}
RMAnnotation *startAnnotation = [[RMAnnotation alloc] initWithMapView:mapView coordinate:((CLLocation *)[coordinates objectAtIndex:0]).coordinate andTitle:#"Start"];
startAnnotation.userInfo = coordinates;
[startAnnotation setBoundingBoxFromLocations:coordinates];
[mapView addAnnotation:startAnnotation];
}
- (RMMapLayer *)mapView:(RMMapView *)mView layerForAnnotation:(RMAnnotation *)annotation
{
if (annotation.isUserLocationAnnotation)
return nil;
RMShape *shape = [[RMShape alloc] initWithView:mView];
// set line color and width
shape.lineColor = [UIColor colorWithRed:0.224 green:0.671 blue:0.780 alpha:1.000];
shape.lineWidth = 8.0;
for (CLLocation *location in (NSArray *)annotation.userInfo)
[shape addLineToCoordinate:location.coordinate];
return shape;
}
What could I be missing? I made a droppoint on the layerForAnnotation method but it isn't being called.
I found the problem I hadn't properly implemented the RMMapViewDelegate. Since it wasn't properly implemented it wasn't called.
Suffices to add it on the header file and assign it in code.
mapView.delegate = self;

Same MKOverlayView delegate called in one UIView but not another. What's missing?

My app tracks GPS movement as a MKPolyline routepath on a MKMapView as an MKOverlayRenderer in the HomeVC, saves the data, and displays it later, as a saved routepath a few VCs deeper, on DisplayVC. I can confirm that the data is identical to the original data on the second VC, and the proper routeBounds are used when the map is shown, but the OverlayRenderer is never called on the second VC. Why not? I'm thinking delegate problems, but I can't find anything wrong.
Both homeVC.h
#interface homeVC : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate> {
and displayVC.h are the same, except for the name:
#interface displayVC : UIViewController <CLLocationManagerDelegate, MKMapViewDelegate> {
CLLocationManager *locationManager;
// the data representing the route points
MKPolyline* _routePath;
// the view we create for the line on the map
MKPolylineView* _routePathVw;
// the rect that bounds the loaded points
MKMapRect _routeBounds;
}
#property (nonatomic, weak) IBOutlet MKMapView *mapView;
#end
And both homeVC.m and displayVC.m are set up the same:
- (void)viewDidLoad {
[super viewDidLoad];
// Add the Map
[_mapView setDelegate:self];
_mapView.mapType = MKMapTypeStandard;
}
Lots of good-working code here. Then,
-(void) buildRoute {
CLLocationCoordinate2D thisCoord;
int i = [arrayLa count] - 1; // keep growing the array size
MKMapPoint *tmpArr = realloc(pointArr, sizeof(CLLocationCoordinate2D)*(arrayLa.count));
pointArr = tmpArr;
thisCoord.latitude = [[arrayLa objectAtIndex:i] floatValue];
thisCoord.longitude = [[arrayLo objectAtIndex:i] floatValue];
MKMapPoint point = MKMapPointForCoordinate(thisCoord);
pointArr[i] = point;
// Reset Map View Boundaries
if( point.x > ne_Pt.x - 500 ) ne_Pt.x = point.x + 1000;
if( point.y > ne_Pt.y - 500 ) ne_Pt.y = point.y + 1000;
if( point.x < sw_Pt.x + 500 ) sw_Pt.x = point.x - 1000;
if( point.y < sw_Pt.y + 500 ) sw_Pt.y = point.y - 1000;
// create the polyline based on the C-array of map Points
_routePath = [MKPolyline polylineWithPoints:pointArr count:arrayLa.count];
_routeBounds = MKMapRectMake(sw_Pt.x, sw_Pt.y, ne_Pt.x-sw_Pt.x, ne_Pt.y-sw_Pt.y);
// add the routePath overlay to the map, if it isn't empty
if (recState == REC && _routePath != nil) {
// zoom in on the route with the fresh bounding box, routeBounds
[self zoomInOnRoute];
[_mapView addOverlay:_routePath];
}
}
-(void) zoomInOnRoute {
[_mapView setVisibleMapRect:_routeBounds];
}
#pragma mark MKMapViewDelegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolyline *route = overlay;
MKPolylineRenderer *routeRenderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
routeRenderer.lineWidth = 3;
routeRenderer.strokeColor = [UIColor redColor];
return routeRenderer;
}
else return nil;
}
Can anyone help solve my problem?
Thanks!
It does look like a delegate issue. Have you tried putting a breakpoint on the addOverLay call just in case the 'if' is skipping it?
I do something similar and all works fine using MKOverlay and MKOverlayRender (based on the apple Breadcrumbs sample app but updated). The app displays a route that the user can save to CoreData. They can select from a table of saved routes and the route is rendered using MKOverlayRenderer.
Set the delegate
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.mapView setDelegate:self];
}
Create a MKOverlay and add to mapView
- (void)createRoute2
{
// Some CoreData stuff. Iterate through map points and create an overlay.
// Order by date ascending so we draw in sequential order
NSSortDescriptor *timeStampDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pointDate" ascending:YES];
NSArray *sortDescriptors = #[timeStampDescriptor];
NSArray *routePts = [[self.selectedRoute mapDetail] sortedArrayUsingDescriptors:sortDescriptors];
// A long is a bit excessive just use an int is fine ( BUT might be a huge number of route points)
long nbrPts = routePts.count;
if (nbrPts < 2){
return;
}
CLLocationCoordinate2D mapPointLoc;
MKMapRect updateRect; // The map area
// Init the route
// FtfmapDetail is a managed object holding lat long (and other stuff)
FtfMapDetail *currentPt = (FtfMapDetail *)[routePts objectAtIndex:0];
mapPointLoc = CLLocationCoordinate2DMake([currentPt.latitude floatValue], [currentPt.longitude floatValue]);
// self.route is a subclassed MapOverlay
if (!self.route)
{
// BGSMapOverlay is a subclassed MapOverlay
self.route = [[BGSMapOverlay alloc] initWithCenterCoordinate:mapPointLoc];
[self.mapView addOverlay:self.route];
}
// Add subsequent points. Kick off the for loop at int position 1 not 0
for (int i=1; i <nbrPts; i++){
currentPt = (FtfMapDetail *)[routePts objectAtIndex:i];
mapPointLoc = CLLocationCoordinate2DMake([currentPt.latitude floatValue], [currentPt.longitude floatValue]);
// AddCoordinate is a method in MKOverlay subclass that returns a bounding MKMaprect for all points in MkOverlay
updateRect = [self.route addCoordinate:mapPointLoc];
}
MKCoordinateRegion region = MKCoordinateRegionForMapRect(self.route.boundingMapRectCompleteRoute);
[self.mapView setRegion:region animated:YES];
}
And make sure you add the delegate method
#pragma mark - MKMapView delegate
// self.routeViewRenderer is a sub-classed MKOverlayRendered (based on the Breadcrumbs app from apple CrumbPathView subclassed MKOverlayView)
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
if (!self.routeViewRenderer)
{
_routeViewRenderer = [[BGSMKOverlayRender alloc] initWithOverlay:overlay];
}
return self.routeViewRenderer;
}
Or it could be that you are not sending any coordinates to the MkPolyLine. In the following snippet if I uncomment the "NSArray *routeCoordinates = [[NSArray alloc]init];" to send a Nil array to the MKPolyLine then the code will run but the delegate doesn't get called. If routeCoordinates contains points then delegate is called and route displayed.
-(void)buildRouteOverlays
{
for (int i=0; i< _routeHeaders.count;i++)
{
_selectedRoute = (FtfMaps*) [_routeHeaders objectAtIndex:i];
NSLog(#"DEBUG route date : %#", _selectedRoute.dateMap);
NSArray *routeCoordinates = [self arrayRoutePointCoordinates];
// if a nil array is produce then MapOverlayRenerder is not called - nothing to render
// Test this by uncommenting:
// NSArray *routeCoordinates = [[NSArray alloc]init];
NSLog(#"DEBUG number of point in Route : %lu",(unsigned long)routeCoordinates.count);
// Just a quick test only process the first route
if (i==0){
MKPolyline *routePolyLine = [self polyLineFromArray:routeCoordinates];
[self.mapView addOverlay:routePolyLine];
}
}
}
-(MKPolyline*)polyLineFromArray:(NSArray*)routePoints
{
NSInteger pointsCount = routePoints.count;
CLLocationCoordinate2D pointsToUse[pointsCount];
for(int i = 0; i < pointsCount; i++) {
FtfMapDetail *mapPt = (FtfMapDetail *) [routePoints objectAtIndex:i];
pointsToUse[i] = CLLocationCoordinate2DMake([mapPt.latitude doubleValue], [mapPt.longitude doubleValue]);
}
MKPolyline *myPolyline = [MKPolyline polylineWithCoordinates:pointsToUse count:pointsCount];
return myPolyline;
}
#pragma mark MKMapViewDelegate
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
if ([overlay isKindOfClass:[MKPolyline class]]) {
MKPolyline *route = overlay;
MKPolylineRenderer *routeRenderer = [[MKPolylineRenderer alloc] initWithPolyline:route];
routeRenderer.lineWidth = 3;
routeRenderer.strokeColor = [UIColor redColor];
return routeRenderer;
}
else return nil;
}

Issues with MKPolyline

I am very new to Xcode and I am facing issues in tracing user path using polyline.
I am getting locations correctly. I am able to add pins properly. However, my polyline method is never called.
Below is my code.
In header file...
#interface Tracker : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate>
{
MKMapView *mapView;
//other declarations
}
Inside implementation file, I have following code. I call, drawPolyline method inside didUpdateLocations method, which is called correctly.
- (void) drawPolyline:(NSArray *)locations
{
NSInteger numberOfLocations = [locations count];
if (numberOfLocations > 1)
{
CLLocationCoordinate2D *locationCoordinate2DArray = malloc(numberOfLocations * sizeof(CLLocationCoordinate2D));
for (int i = 0; i < numberOfLocations; i++)
{
CLLocation* current = [locations objectAtIndex:i];
locationCoordinate2DArray[i] = current.coordinate;
}
self.polyline = [MKPolyline polylineWithCoordinates:locationCoordinate2DArray count:numberOfLocations];
free(locationCoordinate2DArray);
[mapView addOverlay:self.polyline];
[mapView setNeedsDisplay];
}
}
- (MKOverlayView*)mapView:(MKMapView*)mapView viewForOverlay:(id <MKOverlay>)overlay
{
MKPolylineView* polyLineView = [[MKPolylineView alloc] initWithPolyline:self.polyline];
polyLineView.strokeColor = [UIColor blueColor];
polyLineView.lineWidth = 2;
return polyLineView;
}
Your help is highly appreciated. Thanks in advance.
mapView:viewForOverlay: is a delegate method, so you'll need to set the mapview's delegate somewhere. Otherwise, the delegate method will never be called.
[mapView setDelegate:self];

MKMapView freezes on User Interaction

I have an application where I show a small map with one annotation, the map is in a objectDetailScreen that I created, this screen is updated whenever a new object is set, also showing a new map. The map as a annotation for the object.
Whenever I try to move the view, tap the annotations pin or zoom, the map freezes for a while and I have no clue why it does that. The app is iPad only (iPad 2, iOS 4.3.5). Here is the code that sets the map:
- (void) setObject:(AchmeaObject *)_object
{
if(kaart != nil)
{
[kaart removeFromSuperview];
kaart = nil;
}
kaart = [[MKMapView alloc] initWithFrame:CGRectMake(340, 380, 400,300)];
[kaart setDelegate: self];
[kaart setUserInteractionEnabled:YES];
CLLocationCoordinate2D coordinate;
coordinate.latitude = [_object.latitude doubleValue];
coordinate.longitude = [_object.longitude doubleValue];
double miles = 2;
double scalingFactor = ABS( cos(2 * M_PI * coordinate.latitude /360.0) );
MKCoordinateSpan span;
span.latitudeDelta = miles/69.0;
span.longitudeDelta = miles/(scalingFactor*69.0);
MKCoordinateRegion region;
region.span = span;
region.center = coordinate;
[kaart setRegion: region animated:YES];
ObjectAnnotation *sa = [[ObjectAnnotation alloc] initWithName: _object.plaats Address: _object.adres Coordinate:coordinate];
NSArray *anotations = [NSArray arrayWithObject: sa];
[kaart addAnnotations:anotations];
[self.view addSubview:kaart];
}
I have no idea why it happens, but when it first shows it takes a few seconds to respond to any user interaction, and after every interaction it needs at least a few more seconds, until after a few times freezing completely.
ObjectAnnotation.m
#import "ObjectAnnotation.h"
#implementation ObjectAnnotation
#synthesize coordinate = _coordinate;
- (id) initWithName: (NSString *) _name Address: (NSString *) _address Coordinate: (CLLocationCoordinate2D) _coord{
self = [super init];
name = [_name retain];
address = [_address retain];
_coordinate = _coord;
return self;
}
- (NSString *)title {
return name;
}
- (NSString *)subtitle {
return address;
}
- (void)dealloc
{
[name release];
name = nil;
[address release];
address = nil;
[super dealloc];
}
#end
I suspect this is related to re-adding new map views. Add a map view in the xib or very early in the view controller's life cycle and keep it hidden, and then show it and update its position (with setRegion:animated:). Creating a new map view each time is both expensive and unnecessary; if you're doing it because you want to get rid of some state (annotations, the map's region), learn how to reset that state in the existing map view instead.
It could also be related to your ObjectAnnotation, to which you do not provide the source code.
I suffered the same problem. After profiling, I find out tint property could be causing the map refresh delay. So I set default tint at storyboard and problem disappeared.

Resources