MKPointAnnotation not working - objective-c

Hello i got this method:
-(void)adresseZeigen
{
NSLog(#"%s",__PRETTY_FUNCTION__);
selectedAnnotation = [[MKPointAnnotation alloc]init];
selectedAnnotation.title = selectedCompanyName;
selectedAnnotation.subtitle = selectedCompanyAdresse;
selectedAnnotation.coordinate = selectedCompanyPoint;
NSLog(#"selected title: %#",selectedAnnotation.title);
NSLog(#"selected subtitle: %#",selectedAnnotation.subtitle);
NSLog(#"selected latitude is: %f", self.selectedAnnotation.coordinate.latitude );
NSLog(#"selected longitude is: %f", self.selectedAnnotation.coordinate.longitude );
[mapView addAnnotation:selectedAnnotation];
MKCoordinateRegion selectedRegion;
selectedRegion.center = selectedCompanyPoint;
selectedRegion.span.longitudeDelta = 0.01;
selectedRegion.span.latitudeDelta = 0.01;
[mapView setRegion:selectedRegion animated:YES];
}
it should actually give me a annotation in my mapview.
My Log output is:
-[SecondViewController adresseZeigen]
selected title: Company 2
selected subtitle: Company 2 Adresse
selected latitude is: 48.620000
selected longitude is: 9.460000
but somehow I dont get a annotation on map.
Can someone please help me?

This alone is not gonna give you any actual annotation views on the map. In order to have annotation views in your map, you need to declare the MKMapViewDelegate for your view controller, declare it as your mapview delegate and implement the method:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
This is the method that actually produces the annotation view for the map view. In your case you might want to use an MKPinAnnotationView for your MKPointAnnotation!
You can check the protocol reference here.
EDIT: An example implementation of the method (that assumes that all of your MKPointAnnotations have the same purpose) could be:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *reuseId = #"MyReuseID";
MKPinAnnotationView * view = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (!view) {
view = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId];
//custom setup of your view, such as
//view.canShowCallout = YES;
}
return view;
}

Related

Get selected pin coordinate using MapKit framework (Objective-C)

I have a map region with about ten annotated MapPin objects (coordinates retrieved from a plist). In the code below 'locations' is a NSMutable array object containing the pin annotation latitude and longitude.
for (int i = 0; i<[locations count]; i++) {
MKCoordinateSpan span = MKCoordinateSpanMake(0, 0);
CLLocationCoordinate2D center = CLLocationCoordinate2DMake(0, 0);
pinRegion = MKCoordinateRegionMake(center, span);
MapPin *pin = [[MapPin alloc] init];
pinRegion.center.longitude = [locations[i][0] doubleValue];
pinRegion.center.latitude = [locations[i][1] doubleValue];
pin.title = names[i];
pin.coordinate = pinRegion.center;
[self.mapView addAnnotation:pin];
}
By selecting any pin I want to return its coordinate. I can inspect any pin object address like this:
NSLog(#"%#", self.mapView.selectedAnnotations);
... shows a unique address for a selected pin such as "<MapPin: 0x16d2f610>"
But I don't know how to access the objects coordinate properties such as longitude and latitude.
Please can you help?
Thank you!
Make sure your map view has its delegate assigned (in this example we will use your view controller)
mapView.delegate = self
Next handle the callback delegate for annotation taps like this:
Swift
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView)
{
if let annotationCoordinate = view.annotation?.coordinate
{
print("User tapped on annotation with title: \(annotationCoordinate")
}
}
Objective - C
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
NSLog(view.annotation.coordinate);
}
Let me know if you have any questions

MKPinAnnotationView custom Image is replaced by pin with animating drop

I'm displaying user avatar images on a MapView. The avatars appear to be working if they are rendered without animation, however I'd like to animate their drop. If I set pinView.animatesDrop to true, then I lose the avatar and it is replaced by the pin. How can I animate the drop of my avatar without using the pin?
Here is my viewForAnnotation method I'm using:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
MKPinAnnotationView* pinView = (MKPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:#"MyAnnotation"];
if (!pinView) {
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:#"CustomPinAnnotation"];
}
else
pinView.annotation = annotation;
//If I set this to true, my image is replaced by the pin
//pinView.animatesDrop = true;
//I'm using SDWebImage
[pinView setImageWithURL:[NSURL URLWithString:#"/pathtosomeavatar.png"] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
//Adding a nice drop shadow here
pinView.layer.shadowColor = [UIColor blackColor].CGColor;
pinView.layer.shadowOffset = CGSizeMake(0, 1);
pinView.layer.shadowOpacity = 0.5;
pinView.layer.shadowRadius = 3.0;
return pinView;
}
When you want to use your own image for an annotation view, it's best to create a regular MKAnnotationView instead of an MKPinAnnotationView.
Since MKPinAnnotationView is a subclass of MKAnnotationView, it has an image property but it generally (usually when you don't expect it) ignores it and displays its built-in pin image instead.
So rather than fighting with it, it's best to just use a plain MKAnnotationView.
The big thing you lose by not using MKPinAnnotationView is the built-in drop animation which you'll have to implement manually.
See this previous answer for more details:
MKMapView: Instead of Annotation Pin, a custom view
If you're stumbling on to this issue and you're sure that you're MKAnnotationView instead of an MKPinAnnotationView, ensure your MKMapView's delegate property hasn't been nilled.

Passing variable, pushViewControll

I'm trying to build a simple Navigation Controller with a map function. I'm trying to take two variables from the Root view to the Detail view. One have the label and have the longitude.
I get the values from the Root to the Detail'd view but in the log it says this:
2012-04-12 14:38:41.331 Map[80073:11603] long: 0.000000
2012-04-1214:38:41.331 Map [80073:11603] Label
2012-04-12 14:38:41.331 Map[80073:11603] long: 62.375702
Where long is the longitude and label the variable which should be the label. I'm only passing one 'long' variable but always get the 0.00000 first anyway which makes the map show a wrong location and the label won't show anything at all..
I've been trying to figure out what's wrong for hours but can't seem to find anything in the code or on the web so any help is very much appreciated.
RootViewController.m:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *term = #"Label";
float longi1 = 100.102321;
DetailViewController *svc = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:[NSBundle mainBundle]];
//send properties to your view controller
svc.term = term;
svc.longi = longi1;
//push it to the navigationController
[self.navigationController pushViewController:svc animated:YES];
[svc release];
svc = nil;
}
DetailViewController.m:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(term);
NSLog(#"long: %f", longi);
coor.text = term;
float lati = 65.12414;
CLLocationCoordinate2D coord = {.latitude = lati, .longitude = longi};
MKCoordinateSpan span = {.latitudeDelta = 0.5, .longitudeDelta= 0.5};
MKCoordinateRegion region = {coord, span};
[mapView setRegion:region];
[self.view addSubview:mapView];
}
This happens because -initWithNibName:bundle: loads the view in to memory and causes -viewDidLoad to be invoked before you assign the longitude.
Try moving the code in -viewDidLoad to -viewWillAppear

Z-index of iOS MapKit user location annotation

I need to draw the current user annotation (the blue dot) on top of all other annotations. Right now it is getting drawn underneath my other annotations and getting hidden. I'd like to adjust the z-index of this annotation view (the blue dot) and bring it to the top, does anyone know how?
Update:
So I can now get a handle on the MKUserLocationView, but how do I bring it forward?
- (void) mapView:(MKMapView *)aMapView didAddAnnotationViews:(NSArray *)views {
for (MKAnnotationView *view in views) {
if ([[view annotation] isKindOfClass:[MKUserLocation class]]) {
// How do I bring this view to the front of all other annotations?
// [???? bringSubviewToFront:????];
}
}
}
Finally got it to work using the code listed below thanks to the help from Paul Tiarks. The problem I ran into is that the MKUserLocation annotation gets added to the map first before any others, so when you add the other annotations their order appears to be random and would still end up on top of the MKUserLocation annotation. To fix this I had to move all the other annotations to the back as well as move the MKUserLocation annotation to the front.
- (void) mapView:(MKMapView *)aMapView didAddAnnotationViews:(NSArray *)views
{
for (MKAnnotationView *view in views)
{
if ([[view annotation] isKindOfClass:[MKUserLocation class]])
{
[[view superview] bringSubviewToFront:view];
}
else
{
[[view superview] sendSubviewToBack:view];
}
}
}
Update: You may want to add the code below to ensure the blue dot is drawn on top when scrolling it off the viewable area of the map.
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
for (NSObject *annotation in [mapView annotations])
{
if ([annotation isKindOfClass:[MKUserLocation class]])
{
NSLog(#"Bring blue location dot to front");
MKAnnotationView *view = [mapView viewForAnnotation:(MKUserLocation *)annotation];
[[view superview] bringSubviewToFront:view];
}
}
}
Another solution:
setup annotation view layer's zPosition (annotationView.layer.zPosition) in:
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views;
The official answer to that thread is wrong... using zPosition is indeed the best approach and fastest vs using regionDidChangeAnimated...
else you would suffer big performance impact with many annotations on map (as every change of frame would rescan all annotations). and been testing it...
so when creating the view of the annotation (or in didAddAnnotationViews) set :
self.layer.zPosition = -1; (below all others)
and as pointed out by yuf:
This makes the pin cover callouts from other pins – yuf Dec 5 '13 at 20:25
i.e. the annotation view will appear below other pins.
to fix, simply reput the zPosition to 0 when you have a selection
-(void) mapView:(MKMapView*)mapView didSelectAnnotationView:(MKAnnotationView*)view {
if ([view isKindOfClass:[MyCustomAnnotationView class]])
view.layer.zPosition = 0;
...
}
-(void) mapView:(MKMapView*)mapView didDeselectAnnotationView:(MKAnnotationView*)view {
if ([view isKindOfClass:[MyCustomAnnotationView class]])
view.layer.zPosition = -1;
...
}
Update for iOS 14
I know it's an old post, but the question is still applicable and you end up here when typing it into your favorite search engine.
Starting with iOS 14, Apple introduced a zPriority property to MKAnnotationView. You can use it to set up the z-index for your annotations using predefined constants or floats.
Also, Apple made it possible to finally create the view for the user location on our own and provided MKUserLocationView as a subclass of MKAnnotationView.
From the documentation for MKUserLocationView:
If you want to specify additional configuration, such as zPriority,
create this annotation view directly. To display the annotation view,
return the instance from mapView(_:viewFor:).
The following code snippet shows how this can be done (add the code to your MKMapViewDelegate):
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// Alter the MKUserLocationView (iOS 14+)
if #available(iOS 14.0, *), annotation is MKUserLocation {
// Try to reuse the existing view that we create below
let reuseIdentifier = "userLocation"
if let existingView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) {
return existingView
}
let view = MKUserLocationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
view.zPriority = .max // Show user location above other annotations
view.isEnabled = false // Ignore touch events and do not show callout
return view
}
// Create views for other annotations or return nil to use the default representation
return nil
}
Note that per default, the user location annotation shows a callout when tapping on it. Now that the user location overlays your other annotations, you'd probably want to disable this, which is done in the code by setting .isEnabled to false.
Just use the .layer.anchorPointZ property.
Example:
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
views.forEach {
if let _ = $0.annotation as? MKUserLocation {
$0.layer.anchorPointZ = 0
} else {
$0.layer.anchorPointZ = 1
}
}
}
Here is there reference https://developer.apple.com/documentation/quartzcore/calayer/1410796-anchorpointz
Try, getting a reference to the user location annotation (perhaps in mapView: didAddAnnotationViews:) and then bring that view to the front of the mapView after all of your annotations have been added.
Swift 3:
internal func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for annotationView in views {
if annotationView.annotation is MKUserLocation {
annotationView.bringSubview(toFront: view)
return
}
annotationView.sendSubview(toBack: view)
}
}
Here is a way to do it using predicates. I think it should be faster
NSPredicate *userLocationPredicate = [NSPredicate predicateWithFormat:#"class == %#", [MKUserLocation class]];
NSArray* userLocation = [[self.mapView annotations] filteredArrayUsingPredicate:userLocationPredicate];
if([userLocation count]) {
NSLog(#"Bring blue location dot to front");
MKAnnotationView *view = [self.mapView viewForAnnotation:(MKUserLocation *)[userLocation objectAtIndex:0]];
[[view superview] bringSubviewToFront:view];
}
Using Underscore.m
_.array(mapView.annotations).
filter(^ BOOL (id<MKAnnotation> annotation) { return [annotation
isKindOfClass:[MKUserLocation class]]; })
.each(^ (id<MKAnnotation> annotation) { [[[mapView
viewForAnnotation:annotation] superview] bringSubviewToFront:[mapView
viewForAnnotation:annotation]]; });

how to show default user location and a customized annonation view in map kit?

I am using map kit and showing customized annotation view. One is carImage and the another one is userImage(as current location of user). Now I want to show current user location default which is provided by map kit.but unable to show it. How do I show blue circle+my car in map kit?
To show the user location, set the following property to true on the map view object
mapView.showsUserLocation = YES;
To display a custom annotation, set image property on the map view annotation
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
// check for nil annotation, dequeue / reuse annotation
// to avoid over riding the user location default image ( blue dot )
if ( mapView.UserLocation == annotation ) {
return nil; // display default image
}
MKAnnotationView* pin = (MKAnnotationView*)
[mapView dequeueReusableAnnotationViewWithIdentifier: PIN_RECYCLE_ID];
if ( pin == nil ) {
pin = [(MKAnnotationView*) [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier: PIN_RECYCLE_ID] autorelease] ;
pin.canShowCallout = YES;
}
else {
[pin setAnnotation: annotation];
}
pin.image = [UIImage imageNamed:#"car-image.png"];
return pin;
}