How to tell which button is being pressed in calloutAcessoryControlTapped? - ios

I'm using MapKit and I have 2 callout accessories in my pins.
I'm trying to implement a button for updating the pin's title and one for deleting the pin.
Right now, anytime I press a button on the annotation, it only deletes the pin.
How do I get it to respond differently for the right button vs the left button?
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
id <MKAnnotation> annotation = [view annotation];
if ([annotation isKindOfClass:[MKPointAnnotation class]])
{
NSLog(#"Clicked");
if(view.rightCalloutAccessoryView){
[self.mapView removeAnnotation:annotation];
}
else{
float lat= annotation.coordinate.latitude;
float longitude = annotation.coordinate.longitude;
[self.mapView removeAnnotation:annotation];
MKPointAnnotation *pointAnnotation = [[MKPointAnnotation alloc] init];
pointAnnotation.title = _titleOut.text;
pointAnnotation.subtitle = _subtitle.text;
pointAnnotation.coordinate = CLLocationCoordinate2DMake(lat, longitude);
[self.mapView addAnnotation:pointAnnotation];
}
}
}

This line:
if(view.rightCalloutAccessoryView){
says essentially "if view.rightCalloutAccessoryView is not nil".
Since you are setting the right-side accessory on all annotation views, that if condition will always be true and so tapping either accessory will execute the code inside that if which is to remove the annotation.
Instead, you want to check what button or control was tapped in this specific case of the delegate method being called (not whether the view has a right-side accessory defined).
Fortunately, the delegate method passes exactly what control was tapped in the control parameter.
The control parameter can be directly compared against the view's right/left accessory view to tell which was tapped:
if (control == view.rightCalloutAccessoryView) {
Some unrelated points:
The latitude and longitude properties in annotations are of type CLLocationDegrees (aka double) which has higher precision than float so to avoid losing accuracy, use CLLocationDegrees or double:
CLLocationDegrees lat= annotation.coordinate.latitude;
The MKPointAnnotation allows you to change the title directly (it's not read-only like the default id<MKAnnotation>) so you don't need to remove and create a new annotation. It simplifies the code a bit:
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control {
if ([view.annotation isKindOfClass:[MKPointAnnotation class]])
{
NSLog(#"Clicked");
if (control == view.rightCalloutAccessoryView) {
[self.mapView removeAnnotation:view.annotation];
}
else {
// Cast view.annotation as an MKPointAnnotation
// (which we know it is) so that compiler sees
// title is read-write instead of the
// default id<MKAnnotation> which is read-only.
MKPointAnnotation *pa = (MKPointAnnotation *)view.annotation;
pa.title = _titleOut.text;
pa.subtitle = _subtitle.text;
//If you want callout to be closed automatically after
//title is changed, uncomment the line below:
//[mapView deselectAnnotation:pa animated:YES];
}
}
}

Related

FBAnnotationClustering Show Annotation Programmatically

I'm using FBAnnotationClustering in my project. I've hit a wall when coming to display the annotation view programmatically..
eg.
When snapping to a pin on the MapView we'd like to show the annotation.
I've went through the code and can't seem to find where it fires the "show annotation" type function.
The simple answer of mapView selectAnnotation doesn't work since the annotations aren't set with the map and "ERROR: You are trying to select an annotation that has yet been added to the map" appears....
Any ideas?
The Developer of FBAnnotationClustering replied to my issue on GitHub with the following answer.
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
if ([view.annotation isKindOfClass:[FBAnnotationCluster class]]) {
FBAnnotationCluster *cluster = (FBAnnotationCluster *)view.annotation;
int i = 0;
MKMapPoint points[cluster.annotations.count];
for (id<MKAnnotation> annotation in cluster.annotations){
points[i++] = MKMapPointForCoordinate(annotation.coordinate);
}
MKPolygon *polygon = [MKPolygon polygonWithPoints:points count:i];
MKMapRect newMapRect = [polygon boundingMapRect];
[mapView setVisibleMapRect:newMapRect edgePadding:UIEdgeInsetsMake(50, 50, 50, 50) animated:YES];
}
}
The GitHub issue is over here

How to get map annotation title in this method

i want to get annotation title & subtitle from this method.
what the way go get that.
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
//NSString * title = [annotations title];
}
The view has an annotation property that you can use which will return the annotation you originally used when creating the view.

Getting coordinates from pin's annotation's disclosure, on tap

i'll try to keep this very simple :
I'm very new to Objective-C (or programming actually) so i'll probably need an explanation more than just an answer.
What i'm trying to do and can't do (yet):
Getting a pin's coordinate after tapping it's disclosure, and eventually pass it through a segue.
Practically, i'm clicking my "info" icon on a pin I just created, and i'd like to see it's info in another page (a webview). This page would show coordinates (and other stuff that we don't need here).
Why :
Practically, i'm clicking my "info" icon on a pin's annotation created earlier by the user, and i'd like to see it's info in another page (a webview). This page would show coordinates (and other stuff that we don't need here).
My pins coordinates are stored into a
CLLocationCoordinate2D location;
I can't re-use the variables i used before because they might be outdated (it would only work if the user asks for the last one created...)
And I do not know how i can get a pin's coordinates ; there must be a method or something but i jsut can't find it. I've found MANY answers on the internet, and none seemed to work, probably because i didn't understand them properly. Anyway, i couldn't use them.
I'll show you bits of my code, it's pretty straight forward i guess :
There is the viewDidLoad, you probably want to see it, i guess :
- (void)viewDidLoad
{
[super viewDidLoad];
name = [[NSString alloc]init];
detail = [[NSString alloc]init];
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longpressToGetLocation:)];
lpgr.minimumPressDuration = 2.0; //user must press for 2 seconds
[_map addGestureRecognizer:lpgr];
CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(50.837863, 4.353616);
MKCoordinateSpan span = MKCoordinateSpanMake(.035, .035);
MKCoordinateRegion reg = MKCoordinateRegionMake(loc, span);
self.map.region = reg;
[self buildBaseAnno];
self.map.showsUserLocation = true;
}
I know this is important but to be honest i don't fully understand how this bit works ; still, it does work. :D
-(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView* v = nil;
{
static NSString* ident = #"Pin";
v = [_map dequeueReusableAnnotationViewWithIdentifier:ident];
if (v == nil)
{
v = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
((MKPinAnnotationView*)v).pinColor = MKPinAnnotationColorRed;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
v.rightCalloutAccessoryView = infoButton;
v.centerOffset= CGPointMake(0,-20);
v.canShowCallout= YES;
}
v.annotation = annotation;
}
return v;
}
Touch pin creation :
- (void)longpressToGetLocation:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:self.map];
location = [self.map convertPoint:touchPoint toCoordinateFromView:self.map];
[self showAlertName];
}
The actual annotation/pin creation method
-(void)buildAnno
{
CLLocationCoordinate2D coordinate;
coordinate.latitude = location.latitude;
coordinate.longitude = location.longitude;
MKPointAnnotation* newann = [MKPointAnnotation new];
newann.coordinate = coordinate;
newann.title = name;
newann.subtitle = detail;
[self.map addAnnotation:newann];
}
Please, do tell if you need more of the code ; i'm not really sure what i can give you, as my code is probably 'correct' (or decent), i just need to actually know how to get the information i need (that is, coordinates and other stuff from the pin i just tapped.)
And i actually don't tap the pin, i tap the disclosure in the pin's annotation. Anyway, That's enough for now !
Once i can catch these coordinates, i believe i'll be able to pass them through the segue as passing Data is already well explained here, but if there is anything 'special', i'd be really glad if you could add it to your explanation because i'm still really uncomfortable with all this and most of the tutorials/guides/links i've found didn't really help me.
Thank you very much for your time and help :)
(Edit : I had found a similar question here but i believe i need extra help/explanation.)
You don't need the gesture recogniser - the map view delegate protocol already has a method that tells you when the callout accessory was tapped calloutAccessoryControlTapped and this method receives the relevant annotationView. The annotationView.annotation property gets you back to the relevant annotation object and then you can access its coordinate property to get the coordinates of the pin.
First, create a new property in your class:
#property CLLocationCoordinate2D tappedCoord;
then implement the delegate method
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
MKPointAnnotation *annotation=(MKPointAnnotation*)view.annotation;
self.tappedcoord=annotation.coordinate;
[self performSegueWithIdentifier:#"detailViewSegue"]; // Use your appropriate segue identifier
}
Then you can access the property in prepareForSegue (again, change to the appropriate segue name and destination view controller class)
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"detailViewSegue" ]){
DetailViewController *dvc=(DetailViewController *)segue.destinationViewController;
dvc.coord=self.tappedCoord;
}
Also, since your MapView is displaying the user's location, there will be an annotation for that. You need to address this in your viewForAnnotation method, returning nil if the annotation isn't one of yours. You can check the class of the annotation to determine this -
-(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView* v = nil;
if ([annotation isMemberOfClass:[MKPointAnnotation class]]) {
static NSString* ident = #"Pin";
v = [_map dequeueReusableAnnotationViewWithIdentifier:ident];
if (v == nil)
{
v = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
((MKPinAnnotationView*)v).pinColor = MKPinAnnotationColorRed;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
v.rightCalloutAccessoryView = infoButton;
v.centerOffset= CGPointMake(0,-20);
v.canShowCallout= YES;
}
v.annotation = annotation;
}
return v;
}

Ignore MKUserLocation selection to register UILongTapGestureRecognizer

I'm looking to create a 'long hold' pin drop on an MKMapView.
Currently, everything works to the way I want it, when you tap and hold on the Map, it registers the gesture and the code drops a pin.
-(void)viewDidLoad
{
[self.mapView addGestureRecognizer:longPressGesture];
}
-(void)handleLongPressGesture:(UIGestureRecognizer*)sender
{
if(sender.state == UIGestureRecognizerStateBegan || sender == nil)
{
CGPoint point = [sender locationInView:self.mapView];
CLLocationCoordinate2D locCoord;
locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
//Drop Pin
}
}
That is, however, it only works if you are not too close to the MKUserLocation annotation (the Blue pulsing dot) otherwise the gesture does not get registered, and the didSelectAnnotationView: function gets called.
Is there a way to Ignore the user taping the MKUserLocation annotation? I was looking for something like setUserEnabled but it doesn't exist for MKAnnotations.
The MKAnnotationView class has an enabled property (not the id<MKAnnotation> objects).
To set enabled on the map view's user location annotation view, get a reference to it in the mapView:didAddAnnotationViews: delegate method:
-(void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
MKAnnotationView *av = [mapView viewForAnnotation:mapView.userLocation];
av.enabled = NO; //disable touch on user location
}
(In viewForAnnotation, you have to return nil to tell the map view to create the view itself so enabled can't be set there -- at least for the user location.)

Drop a pin on MKMapView

iPhone newbie is here coming from Java. So my objective at this stage is to allow the user to 'drop a pin' on the map. My initialization of the map looks like this:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"your view did load, I'm going to initizlie the map by your location");
CLLocationCoordinate2D location = theMap.userLocation.coordinate;
NSLog(#"Location found from Map: %f %f",location.latitude,location.longitude);
MKCoordinateRegion region;
MKCoordinateSpan span;
NSLog(#"coordinates: %f %f",location.latitude,location.longitude);
if (TARGET_IPHONE_SIMULATOR) {
NSLog(#"You're using the simulator:");
location.latitude = 40.8761620;
location.longitude = -73.782596;
} else {
location.latitude = theMap.userLocation.location.coordinate.latitude;
location.longitude = theMap.userLocation.location.coordinate.longitude;
}
span.latitudeDelta = 0.001;
span.longitudeDelta = 0.002;
region.span = span;
region.center = location;
[theMap setRegion:region animated:YES];
[theMap regionThatFits:region];
[theMap setMapType:MKMapTypeSatellite];
[theMap setZoomEnabled:YES];
[theMap setScrollEnabled:YES];
[theMap setShowsUserLocation:YES];
}
For the requested pin drop I have
- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation {
MKPinAnnotationView *pinView = nil;
if (annotation != theMap.userLocation) {
static NSString *defaultPinID = #"aPin";
pinView = (MKPinAnnotationView *)[theMap dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if (pinView == nil)
pinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
} else {
}
pinView.pinColor = MKPinAnnotationColorRed;
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
return pinView;
}
I'm not sure I fully understand how this map (theMap) works for pins in viewForAnnotation? I mean, what action the user does will activate the viewForAnnotation method? This code doesn't work and I'm not sure why.
I'm using the simulator so I'm not sure if there's a button I should press or Alt click it?
I'm not sure I fully understand how this map (theMap) works for pins in viewForAnnotation?
MKPinAnnotationView is just another kind of annotation view -- that is, you add an annotation (an object conforming to the MKAnnotation protocol) to the map. When the map wants to display the annotation (maybe because the user scrolled the map so that the annotation is in view), it asks you for a view to use to represent the annotation. At that point, your mapView:viewForAnnotation: method can fetch or create a pin annotation view and return that. The user doesn't do anything directly to trigger mapView:viewForAnnotation:, except for scrolling or zooming.
If you want to the user to be able to drop a pin, that's a different thing. You'll need to provide a view (possibly even a MKPinAnnotationView) that they can drag around. When they indicate that they want to drop the pin (perhaps by lifting their finger), you remove the view and add an appropriate annotation at that point. Then the map view will ask you for a view to represent the annotation by calling its delegate's mapView:viewForAnnotation: method.
This code doesn't work and I'm not sure why.
Have you added any annotations to the map? If so, are you looking at the part of the map where they should be displayed?
I'm guessing that you're looking at the animatesDrop property and expecting it to do the entire user pin-dropping interaction. It doesn't do that. Setting that property to YES merely animates the pin as it appears on the map.
ok, after a while, I understood what went wrong:
theMap.delegate = (id) self;
in the constructor was missing. Once I did that any action by end user will activate other methods (protocols) of the map.

Resources