iOS: is it possible to put an annotation at the center of the map and move the map while the annotation remains in the center at all times?

StackOverflow https://stackoverflow.com/questions/21246771

Question

I don't know where to really begin, but I am wondering if it is possible to do this. I know how to put the annotation in mapview at the center.This is what I have so far. If anyone has any idea how to adjust the annotation to center of map when I change regions I will deeply appreciate it.

  - (IBAction)recenter:(id)sender {
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = mapView.centerCoordinate;
pa.title = @"Map Center";
pa.subtitle = [NSString stringWithFormat:@"%f, %f", pa.coordinate.latitude, pa.coordinate.longitude];
[mapView addAnnotation:pa];
self.centerAnnotation = pa;
  }


 - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
centerAnnotation.coordinate = self.mapView.centerCoordinate;
centerAnnotation.subtitle = [NSString stringWithFormat:@"%f, %f", centerAnnotation.coordinate.latitude, centerAnnotation.coordinate.longitude];
   }
Was it helpful?

Solution

Instead of using an annotation, add a subview to the view that holds your map, and set the centers of the 2 views equal to each other. As the user pans the map, it'll look like the annotation is moving.

Then whenever you need to find the coordinate that the center "annotation" is pointing to, you can use the centerCoordinate property of the map view.

I've done this in map box and google maps, but not in MapKit, but I think it should work just the same.

OTHER TIPS

So the annotation isn't really tied to one specific coordinate? You could always create an instance of MKPinAnnotationView and add it as a subview (and not an annotation) to your map view. Since it's a subview of UIView, that should work just fine.

SWIFT 4

You can use this code, but not remains in center, its only for center annotation:

// set 20% less latitude under the center point
userLocation.latitude = userLocation.latitude - self.mapView.region.span.latitudeDelta * -0.20

// You can use this method to center map or others...             
let viewRegion = MKCoordinateRegion(center: userLocationModified, span: coordinateSpan)
mapView.setRegion(viewRegion, animated: true)

If you need add static view, you can add a simply subview.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top