标注可以精确表示用户需要展示的位置信息,高德地图SDK提供的标注功能允许用户自定义图标和信息窗,同时提供了标注的点击、拖动事件的回调。
SDK 提供的地图标注为MAAnnotation类,不同的标记可以根据图标和改变信息窗的样式和内容加以区分。
添加默认样式点标记
iOS SDK提供的大头针标注MAPinAnnotationView,通过它可以设置大头针颜色、是否显示动画、是否支持长按后拖拽大头针改变坐标等。在地图上添加大头针标注的步骤如下:
(1) 修改ViewController.m文件,在viewDidAppear方法中添加如下所示代码添加标注数据对象。
MAPointAnnotation *pointAnnotation = [[MAPointAnnotation alloc] init];
pointAnnotation.coordinate = CLLocationCoordinate2DMake(39.989631, 116.481018);
pointAnnotation.title = @"方恒国际";
pointAnnotation.subtitle = @"阜通东大街6号";
[_mapView addAnnotation:pointAnnotation];
let pointAnnotation = MAPointAnnotation()
pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: 39.979590, longitude: 116.352792)
pointAnnotation.title = "方恒国际"
pointAnnotation.subtitle = "阜通东大街6号"
mapView.addAnnotation(pointAnnotation)
(2) 实现 协议中的 mapView:viewForAnnotation:回调函数,设置标注样式。 如下所示:
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id )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;
}
func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
if annotation.isKind(of: MAPointAnnotation.self) {
let pointReuseIndetifier = "pointReuseIndetifier"
var annotationView: MAPinAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier) as! MAPinAnnotationView?
if annotationView == nil {
annotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
}
annotationView!.canShowCallout = true
annotationView!.animatesDrop = true
annotationView!.isDraggable = true
annotationView!.rightCalloutAccessoryView = UIButton(type: UIButtonType.detailDisclosure)
let idx = annotations.index(of: annotation as! MAPointAnnotation)
annotationView!.pinColor = MAPinAnnotationColor(rawValue: idx!%3)!
return annotationView!
}
return nil
}
运行程序,在地图显示对应的标注点,点击标注弹出气泡,效果如图:
添加自定义样式点标记
iOS SDK可自定义标注(包括自定义标注图标和 自定义气泡图标),均通过MAAnnotationView来实现。
自定义标注图标
若大头针样式的标注不能满足您的需求,您可以自定义标注图标。步骤如下:
(1) 添加标注数据对象,可参考大头针标注的步骤(1)。
(2) 导入标记图片文件到工程中。这里我们导入一个名为 restauant.png 的图片文件。
(3) 在 协议的回调函数mapView:viewForAnnotation:中修改 MAAnnotationView 对应的标注图片。示例代码如下:
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id)annotation
{
if ([annotation isKindOfClass:[MAPointAn