借助镜头,您可以更改用户的地图视角。在导航期间,您可以使用相机模式来控制地图的行为。若要设置相机模式,请设置地图视图的 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;
自动重新设置地图中心
当用户在导航模式下移动地图时,地图视图的相机模式会从以下模式更改为自由模式。当用户明确按重新居中时,相机会返回以下模式。您可以使用计时器设置退出下一个模式并自动返回到下一个模式之间的时间间隔,从而自动返回以下模式。
示例
以下代码示例会检查用户在导航模式下是否正在移动地图。如果是,则它会设置一个计时器,将相机模式切换到下一个模式,并在 5 秒后将地图居中显示。
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