本篇介绍如何在高德地图中自定义Annotation的CallOutView
本文最后会附上App的Github地址。
之前在网上看到一篇百度地图的自定义CallOutView的方法,但是应用在高德上,一直出现这样那样的问题,下面介绍一种方法,非常的简单,因为官方Demo中已经将自定义方法告诉大家了。
废话不多说,直接上一张自定义后的截图
下面介绍用高德地图如果来做,百度地图和Google地图方法类似
- (void)setSelected:(BOOL)selected animated:(BOOL)animated { if (self.selected == selected) { return; } if (selected) { if (self.calloutView == nil) { /* Construct custom callout. */ self.calloutView = [[CustomCalloutView alloc] initWithFrame:CGRectMake(0, 0, kCalloutWidth, kCalloutHeight)]; self.calloutView.center = CGPointMake(CGRectGetWidth(self.bounds) / 2.f + self.calloutOffset.x, -CGRectGetHeight(self.calloutView.bounds) / 2.f + self.calloutOffset.y); } //add view to calloutView将需要添加的label,button等view add到calloutView上。 [self addSubview:self.calloutView]; } else { [self.calloutView removeFromSuperview]; } [super setSelected:selected animated:animated]; }
//customer annotation - (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation { if ([annotation isKindOfClass:[MAPointAnnotation class]]) { static NSString *customReuseIndetifier = @"customReuseIndetifier"; CustomAnnotationView *annotationView = (CustomAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier]; if (annotationView == nil) { annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier]; // must set to NO, so we can show the custom callout view. annotationView.canShowCallout = NO; //注意这个地方一定要设置成NO,不然就是Callout出系统的calloutview。 annotationView.draggable = YES; annotationView.calloutOffset = CGPointMake(0, -5); } annotationView.portrait = [UIImage imageNamed:@"write_p.png"]; //这个是annotation的image,可以在这里进行设置 } return annotationView; } return nil; }
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view { /* Adjust the map center in order to show the callout view completely. */ if ([view isKindOfClass:[CustomAnnotationView class]]) { CustomAnnotationView *cusView = (CustomAnnotationView *)view; CGRect frame = [cusView convertRect:cusView.calloutView.frame toView:self.mapView]; frame = UIEdgeInsetsInsetRect(frame, UIEdgeInsetsMake(kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin, kCalloutViewMargin)); if (!CGRectContainsRect(self.mapView.frame, frame)) { /* Calculate the offset to make the callout view show up. */ CGSize offset = [self offsetToContainRect:frame inRect:self.mapView.frame]; CGPoint theCenter = self.mapView.center; theCenter = CGPointMake(theCenter.x - offset.width, theCenter.y - offset.height); CLLocationCoordinate2D coordinate = [self.mapView convertPoint:theCenter toCoordinateFromView:self.mapView]; [self.mapView setCenterCoordinate:coordinate animated:YES]; } } }
如果有任何问题欢迎再下面留言,或者扫描二维码