攝影機可讓您變更使用者的地圖視角。您可以使用攝影機模式,在導覽期間控制地圖的行為。如要設定攝影機模式,請設定地圖檢視區塊的 cameraMode
屬性,並指定下列其中一個攝影機模式常數:
跟隨:導航的預設攝影機模式。將視角變更為 45 度,並將攝影機放在目前位置後方,朝行進方向拍攝。導航期間,相機會自動調整方向,朝向行進方向。按下地圖的「重新置中」按鈕也會切換至這個模式。選取這個模式時,系統不會顯示「重新置中」按鈕。
總覽:顯示整條路線的總覽,並視需要縮放,將路線納入地圖檢視畫面。選取這個檢視畫面後,系統會顯示「重新置中」按鈕。
Free:使用者可透過手勢變更地圖檢視畫面。 攝影機在這種檢視畫面中會保持靜止。如果使用者在導航期間平移或縮放地圖,地圖就會自動進入這個檢視畫面。選取這個檢視畫面時,系統會顯示「重新置中」按鈕。
如要變更攝影機模式,請設定地圖檢視區塊的 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