Adding and removing annotations from MapView leads to a blink - iphone

in my app I'm adding and removing annotations to my map view, but actually even if I first add the new ones and then remove the old ones there is a blink of the annotations
The new annotations are received from the internet and so I can't just remove them from the array of the new ones...
My question is how does it come to the blink behavior and how I can avoid this?
I don't want to iterate through the annotations and compare each's location...
So I tried to delay the remove and ended up at 0.2 seconds. With exactly this delay there is no visible blink, but this isn't desirable at all.
Thanks
NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray:[_mapView annotations]];
[annotationsToRemove removeObject:[_mapView userLocation]];
[_mapView addAnnotations:locations];
// [_mapView performSelector:#selector(removeAnnotations:) withObject:annotationsToRemove afterDelay:0.2];
[_mapView removeAnnotations:annotationsToRemove];
("locations" is my array of new annotations)

The blink always happens when adding an annotation just after removing one. If you have control of the web service, add a unique id, check if an annotation with that id already exists on your map and only add a new annotation if it doesn't. If you can't add an id, check using the latitude and longitude (which should probably be unique). Iterating through them won't be expensive.

Related

iOS Moving annotations on MapBox map

Is it possible to move an annotation without removing and adding a new annotation?
I'd like to stick with MapBox because the future support of offline maps.
Thank you in advance!!
As of Mapbox iOS SDK v3.2.0, it is not possible to update the coordinates of an annotation that has been added to a map. Here is the relevant ticket on Github.
You can do a custom development for moving marker. I have done it and it's work as expected.
If you want to move a marker along your polyline, I would start by holding a reference to your MGLPointAnnotation and update its coordinate property on a timer or as the user moves along with it.
You can do this by keeping a reference to the annotation instance and then updating the coordinates of that instance.
If I assume you're adding your map (MGLMapView) to a View Controller, then a basic approach could be to add a property to that view controller so that you can keep track of the reference. For this example, I'll use an MGLPointAnnotation:
class ViewControllerWithAMap: UIViewController {
var movingPointAnnotation: MGLPointAnnotation?
...
}
Make this reference an optional so that you know when to initiate it and then just update the coordinates. The last part may seem counterintuitive, but all you really need to do now is add the annotation to the map again. For example:
if self.movingPointAnnotation == nil {
self.movingPointAnnotation = MGLPointAnnotation()
}
guard self.movingPointAnnotation != nil else {
print("What?! Could not initiate moving annotation.")
return // something weird, give up
}
self.movingPointAnnotation!.coordinate = myNewCLLocationCoordinate2D
self.mapView.addAnnotation(self.movingPointAnnotation!)
Regarding that last part where you add the annotation over and over again, I tried only adding the annotation once, and then just updating its coordinates afterward, but the annotation did not move.

Reload or Refresh the MKMapView based on the different preferences or sort types

I have an application where the map view has several pins and annotations. These pins should refresh or reload based on the various sort options I have on my view. e.g. The pins represent various buildings, and the filter options are like, Library, Museum, Movie Theater, All Attractions, etc.
I have tried using
[MapView reloadInputViews];
based on the filtered array after choosing an option. But it simply does not work for me. Any ideas how this would be implemented?
Thanks in advance!
Use [MKMapView removeAnnotations:] and [MKMapView addAnnotation:] to change the pins that are on the map.
As your filter options are totally different entities, you should simply remove all pins on your map and then loop the appropriate array with new filtered datas for adding new pins.
remove all Annotations using [MKMapView removeAnnotations:] 2. recreate the annotation array based on the new sorting 3. add the new annotation to the map

Remove labels using WhirlyGlobe

I am using the (really cool) WhirlyGlobe (https://code.google.com/p/whirlyglobe/) 3D globe display for iPhone in a new application. I can add labels at certain locations using the code shown below. I want to be able to go back and remove a label I added earlier. The Documentation (http://whirlyglobedocs.s3-website-us-east-1.amazonaws.com/html/interface_label_layer.html#ac17e1ec72e70eec416cb2cac833f46fa) shows a removeLabel method but I cannot seem to get it to work. I can add but not remove Labels. I tried looping through all subviews but cannot find these SimpleLabel instances. Can someone please help me understand how to remove a label? I haven't had much luck finding many examples. Thank you!
// Current position
float lat = [[values objectAtIndex:8] floatValue];
flaot lon = [[values objectAtIndex:9] floatValue];
// Create a SingleLabel at this Lat / Lon pair location
SingleLabel *interimLabel = [[[SingleLabel alloc] init] autorelease];
interimLabel.text = [NSString stringWithFormat:#"PRN %d",[[values objectAtIndex:1] intValue]];
[interimLabel setLoc:GeoCoord::CoordFromDegrees(lon, lat)];
[locationArray addObject:interimLabel];
[allLabels addObject:interimLabel];
When you add a single label or a group of labels to the label layer, you'll get back a SimpleIdentity. Keep that around somewhere. Then, when you want to delete the label (or group of labels) from the label layer, you pass back in that SimpleIdentity.
What's going on is this. WhirlyGlobe batches drawable data like a mofo. Your SingleLabel objects no longer exist as soon as the Label Layer has crunched them down into as few Drawables and it can get away with. So to refer to those labels, you have to keep around the unique ID.
Now if you want to delete these labels separately or individually change their appearances, then you've got to add them one by one. One label to one SimpleIdentity. Otherwise there's no way to refer to them individually.
For speed, I recommend grouping as many of them together as you can get away with. If that's just too complex for now, add them one by one and then make a note to come back. So when you say "Why isn't this running as fast as I'd like" you can then say "Ooooo, right."

Toubleshooting mapkit performance

I'm plotting over 500 points on a map using mapkit. Zooming is a little jittery compared to the native google map app. I've discovered what is causing the slowness. I'm adding custom annotations so that I can later add different pin colors and buttons for detail views:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(AddressNote *) annotation {
MKPinAnnotationView *annView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"currentlocation"];
annView.pinColor = MKPinAnnotationColorGreen;
annView.animatesDrop=TRUE;
annView.canShowCallout = YES;
annView.calloutOffset = CGPointMake(-5, 5);
return annView;
}
If I comment out the above code, everything works fine. Very smooth with zooming in/out. Should I be adding annotations differently to boost performance?
500 annotations is probably too many, but not so many that the performance suffers when you are only viewing some of them. However, you should be using dequeueing with your annotations to improve performance
- (MKAnnotationView *)mapView:(MKMapView *)mapView
viewForAnnotation:(id <MKAnnotation>)annotation
{
MKPinAnnotationView *view = nil;
if (annotation != mapView.userLocation) {
view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:#"identifier"];
if (nil == view) {
view = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"identifier"] autorelease];
}
[view setPinColor:MKPinAnnotationColorGreen];
[view setCanShowCallout:YES];
[view setAnimatesDrop:NO];
}
else {
// Do something with the user location view
}
return view;
}
Also, with 500 pins, the drop animation takes a long time to finish. You should turn that off with [view setAnimatesDrop:NO]
I wrote an iPhone app for a client and we included a store locator for one of their store brands. It includes 501 locations and while the animation can be a bit jerky when you are zoomed out to view the entire United States, it's perfectly fine zoomed in to the state level, where only a handful of pins are visible.
The keys:
Zoom the user into their current location before you add your annotations.
Reuse annotation views using dequeueReusableAnnotationViewWithIdentifier:.
To achieve the first point, you need to turn on location updates and set a flag when you receive the first one. Animate the map to that location using a region span that makes sense for your app, then in mapView:regionDidChangeAnimated:, check to see if you still need to add your annotations and that the current location has been updated before you call addAnnotation:.
If you can't or don't want to zoom in to the user's location, can you filter the annotations shown at the highest level and only add additional annotations as the user zooms in?
By the way, I believe you have a memory leak in your code as posted above. Even if you don't want to use the dequeuing mechanism, the view you return from mapView:viewForAnnotation: should be autoreleased.
I think St3fan is correct. In theory you can just keep adding annotations to the map and let the view handle display of them, but the reality is that it's better if you keep the count down a bit, 500 on screen at once would be way too many to see anyway.
However there is one more step to try - make sure all of the annotation views have opaque set to YES like so:
annView.opaque = YES;
It sounds to me that adding 500 map points to a section of a map the size of the iPhone screen makes no sense. There is no way you can visualize that or even click on the right annotation.
Can't you look at the zoom level and center of the map and then decide to only add a subset of annotations to the map?
I think I've seen other apps do this too.
If you are not removing annotations not seen by user from view, that is one thing to do by means of MKMapViewDelegate.
If performance is degrading when user zoom-out to country level you may want to present aggregated info on zoom levels > some const value, e.g. instead of 30 annotations within 10 square miles show single annotation like [30 something].

MKMapView loading all annotation views at once (including those that are outside the current rect)

UPDATE
It looks like this problem has been quietly fixed in iOS 4.3. Up to this point, the distance that was considered "far enough" for an annotation to be recycled seemed to be hundreds of miles, even when zoomed in very closely. When I build my app with the iOS 4.3 SDK, annotations are recycled based on more reasonable limits.
Has anyone else run into this problem? Here's the code:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(WWMapAnnotation *)annotation {
// Only return an Annotation view for the placemarks. Ignore for the current location--the iPhone SDK will place a blue ball there.
NSLog(#"Request for annotation view");
if ([annotation isKindOfClass:[WWMapAnnotation class]]){
MKPinAnnotationView *browse_map_annot_view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:#"BrowseMapAnnot"];
if (!browse_map_annot_view) {
browse_map_annot_view = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"BrowseMapAnnot"] autorelease];
NSLog(#"Creating new annotation view");
} else {
NSLog(#"Recycling annotation view");
browse_map_annot_view.annotation = annotation;
}
...
As soon as the view is displayed, I get
2009-08-05 13:12:03.332 xxx[24308:20b] Request for annotation view
2009-08-05 13:12:03.333 xxx[24308:20b] Creating new annotation view
2009-08-05 13:12:03.333 xxx[24308:20b] Request for annotation view
2009-08-05 13:12:03.333 xxx[24308:20b] Creating new annotation view
and on and on, for every annotation (~60) I've added. The map (correctly) only displays the two annotations in the current rect. I am setting the region in viewDidLoad:
if (center_point.latitude == 0) {
center_point.latitude = 35.785098;
center_point.longitude = -78.669899;
}
if (map_span.latitudeDelta == 0) {
map_span.latitudeDelta = .001;
map_span.longitudeDelta = .001;
}
map_region.center = center_point;
map_region.span = map_span;
NSLog(#"Setting initial map center and region");
[browse_map_view setRegion:map_region animated:NO];
The log entry for the region being set is printed to the console before any annotation views are requested.
The problem here is that since all of the annotations are being requested at once, [mapView dequeueReusableAnnotationViewWithIdentifier] does nothing, since there are unique MKAnnotationViews for every annotation on the map. This is leading to memory problems for me.
One possible issue is that these annotations are clustered in a pretty small space (~1 mile radius). Although the map is zoomed in pretty tight in viewDidLoad (latitude and longitude delta .001), it still loads all of the annotation views at once.
Thanks...
What you would expect is some kind of "clipping" of the annotation views based on the current region the map displays.
This is NOT the way the dequeueReusableAnnotationViewWithIdentifier selector works.
From its documentation :
As annotation views move offscreen, the map view moves them to an internally managed reuse queue. As new annotations move onscreen, and your code is prompted to provide a corresponding annotation view, you should always attempt to dequeue an existing view before creating a new one.
So the reusable mechanism only makes sense when you invoke a sequence like :
//this will create 1000 annotation views
[theMap addAnnotations:my1000annotations];
//this will move them offscreen (but some annotation views may be kept internally for further reuse)
[theMap removeAnnotatios:theMap.annotations];
//when adding back again some annotations onscreen, some of the previous annotation views will be reused.
[theMap addAnnotations:someNew400annotations];
In you case, the way I would implement the clipping (to display only the annotation for the current displayed region) is :
Add a delegate to your mapView and implement the - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated method to get informed when the region has changed
iterate through all your objects to get the ones that match this region
addAnnotations to your map for only those objects (you can implement a kind of merge between the previously displayed annotations and the new one or simply restart from scratch , remove all annotations, and set the new ones
Of course, when the user zooms out quite a lot and that the scope of the region is too big (too many pins to be displayed), then you have to take a decision : do I displayed all the annotations views (and take the risk that the display on the map does not give much info) or do I set a message to the user saying "zoom in to get pins" or whatever. But this is another story... ;)
Not sure if this will help, but you mentioned memory issues due to load of ~60 objects. Is there a way to conditionally load each object based on the current map region center and current map region span?
// :)