免费开源的iOS开发学习平台

高德地图SDK:4-绘制地图标注

同MapKit框架类似,使用高德地图SDK也可以在地图上添加标注。标注可以精确表示用户需要展示的位置信息,高德地图SDK提供的标注功能允许用户自定义图标和信息窗,同时提供了标注的点击、拖动事件的回调。高德地图SDK提供的地图标注为MAAnnotation类,不同的标记可以根据图标和改变信息窗的样式和内容加以区分。

添加默认样式点标记

高德地图SDK提供的大头针标注MAPinAnnotationView,通过它可以设置大头针颜色、是否显示动画、是否支持长按后拖拽大头针改变坐标等。在地图上添加大头针标注的步骤如下:

  • 修改ViewController.m文件,在viewDidAppear方法中添加如下所示代码添加标注数据对象
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //添加大头针
    MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
    pointAnnotation.coordinate = CLLocationCoordinate2DMake(32.03522, 118.74237);
    pointAnnotation.title = @"侵华日军南京大屠杀遇难同胞纪念馆";
    pointAnnotation.subtitle = @"水西门大街418号";
    [self.mapView addAnnotation:pointAnnotation];
    self.mapView.centerCoordinate = pointAnnotation.coordinate;
}
  • 实现MAMapViewDelegate协议中的 mapView:viewForAnnotation:回调函数,设置标注样式。
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= YES;       //设置气泡可以弹出,默认为NO
        annotationView.animatesDrop = YES;        //设置标注动画显示,默认为NO
        annotationView.draggable = YES;        //设置标注可以拖动,默认为NO
        annotationView.pinColor = MAPinAnnotationColorPurple;
        return annotationView;
    }
    return nil;
}

运行后,可以在地图上展示地图标注。