-->

Custom curent location Annotation pin not updating

2019-06-02 10:54发布

问题:

Trying to add a custom pin for current location, However the location does not update. Even after setting setShowsUserLocation = YES;

- (id)initWithAnnotation:(id <MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier {

    self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
    if ([[annotation title] isEqualToString:@"Current Location"]) {
        self.image = [UIImage imageNamed:[NSString stringWithFormat:@"cursor_%i.png", [[Session instance].current_option cursorValue]+1]];
    }

However, if I set to return nil; everything works fine, but I lose the custom image. I really want to get this to work. Any help would be greatly appreciated.

回答1:

As you've seen the setShowsUserLocation flag only shows the current location using the default blue bubble.

What you need to do here listen for location updates from the phone and manually reposition your annotation yourself. You can do this by creating a CLLocationManager instance and remove and replace your annotation whenever the Location Manager notifies its delegate of an update:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
  // update annotation position here
}

To reposition the coordinates, I have a class, Placemark, that conforms to the protocol MKAnnotation:

//--- .h ---

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface Placemark : NSObject <MKAnnotation> {
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *strSubtitle;
@property (nonatomic, retain) NSString *strTitle;

-(id)initWithCoordinate:(CLLocationCoordinate2D) coordinate;
- (NSString *)subtitle;
- (NSString *)title;

@end

//--- .m ---

@implementation Placemark

@synthesize coordinate;
@synthesize strSubtitle;
@synthesize strTitle;

- (NSString *)subtitle{
    return self.strSubtitle;
}
- (NSString *)title{
    return self.strTitle;
}

-(id)initWithCoordinate:(CLLocationCoordinate2D) c {
    self.coordinate = c;
    [super init];
    return self;
}

@end

Then in my mapview controller I place the annotation with:

- (void) setPlacemarkWithTitle:(NSString *) title andSubtitle:(NSString *) subtitle forLocation: (CLLocationCoordinate2D) location {

    //remove pins already there...
    NSArray *pins = [mapView annotations];

    for (int i = 0; i<[pins count]; i++) {
      [mapView removeAnnotation:[pins objectAtIndex:i]];
    }

    Placemark *placemark=[[Placemark alloc] initWithCoordinate:location];
    placemark.strTitle = title;
    placemark.strSubtitle = subtitle;
    [mapView addAnnotation:placemark];  
    [self setSpan]; //a custom method that ensures the map is centered on the annotation 
}