自定义锚点

来源:互联网 发布:淘宝天下网商店小二 编辑:程序博客网 时间:2024/06/16 04:15
#import "ViewController.h"
#import <MapKit/MapKit.h>

@interface ViewController ()<MKMapViewDelegate>
{
    MKMapView *_mapView ;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds] ;
    
    _mapView.delegate = self ;
    
    [self.view addSubview:_mapView] ;
    
    CLLocationCoordinate2D center ; // 地图的中心位置
    center.latitude = 40.82 ; // 纬度
    center.longitude = 114.88 ; // 经度
    
    MKCoordinateSpan span ; // 显示范围
    span.latitudeDelta = 0.5 ;
    span.longitudeDelta = 0.5 ;
    
    MKCoordinateRegion region = {center,span} ; // 显示区域
    
    [_mapView setRegion:region animated:YES] ; // 地图显示的区域
    
    
    // 添加锚点
    MKPointAnnotation *pointAnno = [[MKPointAnnotation alloc] init] ;
    pointAnno.title = @"河北省" ;
    pointAnno.subtitle = @"张家口市" ;
    
    pointAnno.coordinate = center ;
    // 添加锚点到地图
    [_mapView addAnnotation:pointAnno] ;
    
    
}
// 自定义锚点
- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
    
    MKAnnotationView *anno = [mapView dequeueReusableAnnotationViewWithIdentifier:@"reuse"] ;
    if (!anno) {
        anno = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"reuse"] ;
    }
    
    anno.image = [UIImage imageNamed:@"8.png"] ;
    anno.canShowCallout = YES ; // 可以调出 ?
    
    return anno ;
}