I am writing an iOS 5 app which tracks a user’s location in real-time, plotting their course on a MKMapView. Whenever a GPS reading is taken I would like a polyline to be drawn between the current and old locations, eventually forming a track (or breadcrumb) of where the user has travelled.
I am comfortable with using MKPolyline and MKPolylineView to draw a track, assuming that I have all the CLLocationCoordinate2D coordinates in advance, using code similar to below:
MKPolyline *route = [MKPolyline polylineWithCoordinates:coordinates count:[self.coordinateArray count]];
[mapView addOverlay:route];
However, since I am only getting the CLLocationCoordinate2D coordinates in real-time (as the locationManager:didUpdateToLocation:fromLocation: delegate method is called) I am unsure of the best way to draw the new polylines.
Can I extend the existing lines (i.e. adding to the C-based coordinates array – not having much C experience I am unsure how to do this) or do I need to create a new polyline between the next two coordinates (although I have heard that having too many individual polylines on the map can impact performance and memory usage…)?
Thanks in advance.
First, see how to update MKPolyline / MKPolylineView?, especially the link to the the Breadcrumb sample code. It may be a good starting point for what you need.
However, you’ll see that a vital part of its
CrumbPathobject is a call torealloc. So yes, you need to know how to manage C-style arrays if you want to efficiently store your arrays of points. Yes, this is not easy. Yes, C-style array manipulation is an invitation for memory leaks.The Breadcrumb sample uses
reallocto resize its array. You can be a bit safer by allocating the memory the array uses with theNSMutableDatatype. It is recommended as an answer to Is it ok to use “classic” malloc()/free() in Objective-C/iPhone apps?. Read the other solutions to see regular Cmalloc()andfree()functions doing the same job. Note that NSMutableData has a very handyincreaseLengthBy:method.When you understand why every C student attempts to use
sizeof()incorrectly – and how to use it properly – you will understand C memory management.