借助摄像头,您可以更改用户查看地图的
视角。您可以使用摄像头模式来控制导航期间地图的行为。如需设置摄像头模式,请设置地图视图的 cameraMode 属性,并指定以下摄像头模式常量之一:
跟随模式 - 导航的默认摄像头模式。将视角更改为 45 度,并将摄像头置于当前位置后方,朝向行进方向。在导航期间,摄像头会自动调整为朝向行进方向。按地图的重新居中 按钮也会切换到此模式。选择此模式后,重新居中 按钮不可见。
概览模式 - 显示整个路线的概览,并根据需要进行缩放,以使路线适合地图视图。选择此视图后,重新居中 按钮可见。
自由模式 - 让用户通过手势更改地图视图。 在此视图中,摄像头保持静止。如果用户在导航期间平移或缩放,地图会自动进入此视图。选择此视图后,重新居中 按钮可见。
如需更改摄像头模式,请设置地图视图的 cameraMode 属性,如下所示:
Swift
// Set the mode to "overview":
mapView.cameraMode = .overview
// Set the mode to "free":
mapView.cameraMode = .free
// Set the mode to "following":
mapView.cameraMode = .following
Objective-C
// Set the mode to "overview":
mapView.cameraMode = GMSNavigationCameraModeOverview;
// Set the mode to "free":
mapView.cameraMode = GMSNavigationCameraModeFree;
// Set the mode to "following":
mapView.cameraMode = GMSNavigationCameraModeFollowing;
自动重新居中显示地图
当用户在导航模式下移动地图时,地图视图的摄像头模式会从跟随模式更改为自由模式。当用户明确按下重新居中 按钮时,摄像头会返回到跟随模式。您可以使用计时器设置离开跟随模式的时间间隔,然后自动返回到跟随模式,从而自动返回到跟随模式。
示例
以下代码示例会检查以确定用户是否在导航模式下移动地图。如果是,则它会设置一个计时器,以将摄像头模式切换为跟随模式,并在五秒后将地图居中。
Swift
class YourViewController: UIViewController {
@IBOutlet weak var mapView: GMSMapView!
var autoFollowTimer: Timer!
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
...
}
...
}
/** Implements the GMSMapViewDelegate protocol. */
extension YourViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
if mapView.navigator?.isGuidanceActive == false {return}
if !gesture {return}
autoFollowTimer?.invalidate()
autoFollowTimer = Timer(
timeInterval: TimeInterval(5.0),
target: self,
selector: #selector(recenterMap),
userInfo: nil,
repeats: false)
RunLoop.current.add(autoFollowTimer, forMode: .default)
}
/** Centers the map in guidance mode. */
@objc private func recenterMap() {
if mapView.navigator?.isGuidanceActive == true {
mapView.cameraMode = .following
}
autoFollowTimer.invalidate()
autoFollowTimer = nil
}
}
Objective-C
@interface YourViewController : UIViewController<GMSMapViewDelegate>
...
@end
@implementation YourViewController {
GMSMapView *_mapView;
NSTimer *_autoFollowTimer;
...
}
...
- (void)viewDidLoad {
[super viewDidLoad];
...
_mapView.delegate = self;
...
}
...
/** Implements the GMSMapViewDelegate protocol. */
- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture {
if (!_mapView.navigator.guidanceActive) return;
if (!gesture) return;
[_autoFollowTimer invalidate];
_autoFollowTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:@selector(recenterMap)
userInfo:nil
repeats:NO];
}
/** Centers the map in guidance mode. */
- (void)recenterMap {
if (_mapView.navigator.guidanceActive) {
_mapView.cameraMode = GMSNavigationCameraModeFollowing;
}
[_autoFollowTimer invalidate];
_autoFollowTimer = nil;
}
@end