iOS百度地图 根据两个经纬度计算角度

上代码

1.首先计算斜率方法: fromCoord是上一个经纬度 , toCoord是下一个经纬度
- (double)getSlopWithFromCoord:(CLLocationCoordinate2D)fromCoord toCoord:(CLLocationCoordinate2D)toCoord {
    double fromLat = fromCoord.latitude;
    double fromlon = fromCoord.longitude;
    double toLat = toCoord.latitude;
    double tolon = toCoord.longitude;

    if (tolon == fromlon) {
        return MAXFLOAT;
    }
    double slope = ((toLat - fromLat) / (tolon - fromlon));
    return slope;

}
2.计算角度方法: fromCoord是上一个经纬度 , toCoord是下一个经纬度
分四个象限计算,同时判断x和y轴
- (double)getAngleWithFromCoord:(CLLocationCoordinate2D)fromCoord toCoord:(CLLocationCoordinate2D)toCoord {
    double fromLat = fromCoord.latitude;
    double fromlon = fromCoord.longitude;
    double toLat = toCoord.latitude;
    double tolon = toCoord.longitude;
    
    double slope = [self getSlopWithFromCoord:fromCoord toCoord:toCoord];
    
    if (slope == MAXFLOAT) {
        if (toLat > fromLat) {
            return 0;
        } else {
            return 180;
        }
    }
    double radio = atan(slope);
    double angle = 180 * (radio / M_PI);
    if (slope > 0) {
        if (tolon < fromlon) {
            angle = -90 - angle;
        } else {
            angle = 90 - angle;
        }
    } else if (slope == 0) {
        if (tolon < fromlon) {
            angle = -90;
        } else {
            angle = 90;
        }
    } else {
        if (toLat < fromLat) {
            angle = 90 - angle;
        } else {
            angle = -90 - angle;
        }
    }
    return  angle;
}
3.如何使用:
- (void)running {
   HomeCarAnnotationView *carAnnotationView = (HomeCarAnnotationView *)[self.mapView viewForAnnotation:self.currentCarAnntation]; 
   double angle = [self getAngleWithFromCoord:self.fromCoor toCoord:self.toCoor];
   carAnnotationView.imageView.transform = CGAffineTransformMakeRotation(angle*M_PI/180); //此处需要计算最终角度
}
4.图片朝向向上
21F49B2A-0CF9-4865-986F-F19A8248223D.png
5. 如果图片是反向的:
- (void)running {
   HomeCarAnnotationView *carAnnotationView = (HomeCarAnnotationView *)[self.mapView viewForAnnotation:self.currentCarAnntation]; 
   double angle = [self getAngleWithFromCoord:self.fromCoor toCoord:self.toCoor];
   carAnnotationView.imageView.transform = CGAffineTransformMakeRotation(-(angle*M_PI/180)); //此处需要计算最终角度
}

你可能感兴趣的:(iOS百度地图 根据两个经纬度计算角度)