Search code examples
iosobjective-cmkmapviewmapkitmkannotationview

How to move the center of MKMapView so that the default location icon goes to bottom center


I found some of the questions related to this on stackOverflow like this one, this and this one here. The last one actually worked but the problem is I'm using heading in MapKit I mean this (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading. SO the problem now it when I applied this solution:

MKCoordinateRegion oldRegion = [mapView regionThatFits:MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 800.0f, 200.0f)];
    CLLocationCoordinate2D centerPointOfOldRegion = oldRegion.center;

    //Create a new center point (I added a quarter of oldRegion's latitudinal span)
    CLLocationCoordinate2D centerPointOfNewRegion = CLLocationCoordinate2DMake(centerPointOfOldRegion.latitude + oldRegion.span.latitudeDelta/5.0, centerPointOfOldRegion.longitude);

    //Create a new region with the new center point (same span as oldRegion)
    MKCoordinateRegion newRegion = MKCoordinateRegionMake(centerPointOfNewRegion, oldRegion.span);

    //Set the mapView's region
    [_mapView setRegion:newRegion animated:NO];

It successfully updates but as I move my phone and the accelometer is accessed it started a jerking effect between the newRegion and oldRegion. Any sggestions how?

UPDATE
I found this method which was let me change the default image of the userLocation annotation and this has a property which I can set like myAnnotaton.center so any ideas here that this might work or how to set its center?

- (MKAnnotationView *)mapView:(MKMapView *)mapView
            viewForAnnotation:(id<MKAnnotation>)annotation {


    if (annotation==(mapView.userLocation)) {
        MKAnnotationView *myAnotation = [[MKAnnotationView alloc] init];

        myAnotation.image = [UIImage imageNamed:@"marker"];
        myAnotation.frame = CGRectMake(0, 0, 100, 100);

        return myAnotation;
    }
    else
    {
    return nil;
    }
}

Solution

  • You need to add a delegate method that will overwrite your default annotation.

    - (MKAnnotationView *)mapView:(MKMapView *)mapView
                viewForAnnotation:(id<MKAnnotation>)annotation {
    
    
        if (annotation==(mapView.userLocation)) {
            MKAnnotationView *myAnotation = [[MKAnnotationView alloc] init];
    
            myAnotation.image = self.userPointImage.image; //give any image here
            myAnotation.centerOffset = CGPointMake(0, 250);
    
            return myAnotation;
        }
        else
        {
        return nil;
        }
    }
    

    The centerOffset will set the annotation to the bottom and the map will rotate accordingly to it