当前位置的注释 Pin 未出现

Annotation Pin for current location not appearing

我试图利用地图工具包使用 MKMapView 及其委托方法显示我的当前位置,didUpdateUserLocation但是当我放大并非常接近时,我会看到多个图钉。然后在我意识到一些建议之后,每次都会更新位置,重新创建 pin。所以,我从委托方法中取出了我的添加注释代码。

这是我的代码-

#import "MapViewController.h"
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>


@interface MapViewController ()<MKMapViewDelegate, CLLocationManagerDelegate, UITextFieldDelegate> {
    MKPointAnnotation *myAnnotation;
}
@property (nonatomic, strong) IBOutlet MKMapView *mapView;
@property (nonatomic, strong) IBOutlet UITextField *searchTextField;

@property (strong, nonatomic) CLLocationManager *locationManager;

@end

@implementation MapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.mapView.delegate=self;
    self.mapView.showsUserLocation=YES;

    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;

    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
    }

    myAnnotation = [[MKPointAnnotation alloc]init];
    myAnnotation.coordinate = self.mapView.userLocation.coordinate;
    myAnnotation.title = @"Current Location";
    [self.mapView addAnnotation:myAnnotation];  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark-
#pragma mark- MapView Delegate


- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{

    MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, 800, 800);
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];

}

@end

但是现在没有pin了

亲爱的,您需要将 myAnnotation 代码放在委托方法之外 "didUpdateUserLocation"

注意:您需要在 viewDidLoad 中进行注释,然后使用 didUpdateUserLocation 来更新您的坐标

是的,如果您不想在 mapview 中显示图钉,那么请将其保留在代码之外或将其删除您在 didUpdateUserLocation 中编写的代码。

=> 当您设置 mapView.showsUserLocation = YES:

时,MKMapView 会自动放置 class MKUserLocation 的注释

您可以将此注释的默认视图替换为您想要的任何默认注释视图,方法是在 mapView:viewForAnnotation:

- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation {
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        // replace the following with code to generate and return custom user position annotation view
        return customAnnotationView;
    }

    //*** other code ***//
}