大家都知道,如果需要百度地图当前位置能跟随手机方向而改变方向的话,使用百度地图自身的跟随模式BMKUserTrackingModeFollow就可以做到,但是有个问题,当点击当前滑动地图后,方向就不会改变了;那有没有其他方法能解决这个问题了?
我的做法是:不是用百度地图自身的跟随模式,也不是用百度地图自身的当前位置,而是自己添加一个annotation:
定义三个变量:
MyLocationAnnotation *myLocationAnnotation;
BMKAnnotationView *myLocationAnnotationView;
UIImage *myLocationImage;
一:在百度地图位置更新方法didUpdateBMKUserLocation里面调用下面的方法:
-(void) addMyLocationView {
bmkmapView.showsUserLocation = NO;
if(nil == myLocationAnnotation) {
myLocationAnnotation = [[MyLocationAnnotation alloc] init];
myLocationAnnotation.coordinate = myOutdoorLocation.location.coordinate;
[bmkmapView addAnnotation:myLocationAnnotation];
} else {
myLocationAnnotation.coordinate = myOutdoorLocation.location.coordinate;
}
}
二:在回调方法里面
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{if ([annotation isKindOfClass:[MyLocationAnnotationclass]]) {
NSString *AnnotationViewID = @"locationMark";
BMKPinAnnotationView *animationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
if(animationView ==nil){
animationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
}
animationView.annotation = annotation;
myLocationAnnotationView = animationView;
myLocationImage = animationView.image = [UIImage imageNamed:@"my_loc"];//带箭头方向的图片
animationView.centerOffset = CGPointMake(0, animationView.frame.size.height/2);
return animationView;
}
}
三:在百度地图回调方法didUpdateUserHeading里,根据百度地图放回的方向设置当前位置的方向:
-(void) setUserHeading:(BMKUserLocation*)userHeading {
if(nil == userHeading || nil == userHeading.heading
|| userHeading.heading.headingAccuracy < 0) {
return;
}
CLLocationDirection theHeading = userHeading.heading.magneticHeading;
double d = 360 - theHeading;
float direction = theHeading;
if(nil != myLocationAnnotationView) {
if (direction > 180)
{
direction = 360 - direction;
}
else
{
direction = 0 - direction;
}
myLocationAnnotationView.image = [myLocationImage imageRotatedByDegrees:-direction];
}
}
- (UIImage*) imageRotatedByDegrees:(CGFloat)degrees
{
CGFloat width = CGImageGetWidth(self.CGImage);
CGFloat height = CGImageGetHeight(self.CGImage);
CGSize rotatedSize;
rotatedSize.width = width;
rotatedSize.height = height;
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
CGContextRotateCTM(bitmap, degrees * M_PI / 180);
CGContextRotateCTM(bitmap, M_PI);
CGContextScaleCTM(bitmap, -1.0, 1.0);
CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}