2016-12-26 109 views
1

但是,每當用戶將地圖的相機更新移動到其位置時,我的應用程序都會在用戶位置啓動。我希望它能夠加載到它們的位置,但是即使它們的位置正在移動,也可以讓它們自由瀏覽地圖。類似於Google地圖應用中顯示的行爲。我正在使用KVO來收集viewDidLoad()函數中的位置。該行看起來是這樣的:停止地圖更新用戶位置更新 - Google Maps iOS SDK

mapView.isMyLocationEnabled = true 
self.mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.new, context: nil) 

這是我的觀察功能的代碼:

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { 

    guard let update = change, let myLocation = update[NSKeyValueChangeKey.newKey] as? CLLocation else { 
     print("Location not found") 
     return 
    } 

    self.mapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 14) 

} 

什麼需要改變,以使其符合上述標準。

+0

一旦獲取了myLocation的值,就可以刪除觀察者。因此,它會在地圖上定位您的位置,然後不會再像以下那樣更換攝像機:'observeValue()'方法底部的'self.mapView.removeObserver(self)'。 –

+0

@SunilChauhan這給了我以下錯誤:**終止應用程序,由於未捕獲的異常'NSInternalInconsistencyException',原因:'類GMSMapView的實例0x101f30160被釋放,而鍵值觀察員仍然註冊它。當前觀察信息: Context:0x0,Property:0x174054940> ) * –

回答

0

在Sunil的答案幫助下,我想出瞭如何解決這個問題。

Sunil指出,每次更新用戶的位置時,應用程序都會調用observeValue()。所以根據我在observeValue()中的代碼,這是有道理的,mapView相機將更新每次用戶的位置更新。

我通過移動

self.mapView.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 14) 

另一個函數一樣viewDidAppear()解決了這個問題。

有人可能會問,爲什麼我沒有將它移動到viewDidLoad(),因爲這是之前調用viewDidAppear()。在viewDidLoad()結束之前,應用程序不會獲取用戶的位置。因此,將相機聲明放在viewDidLoad()的末尾不會讓應用程序有足夠的時間獲取用戶位置。通過在viewDidAppear()函數中聲明相機位置,我們可以給應用程序足夠的時間來處理用戶的位置並獲取它。

注意:請務必將您的位置變量從observeValue()函數中移出,以便在viewDidAppear()中使用。

1

使用this助手代碼,就可以得到用戶的位置,並設置喜歡的目標:

CLLocationManager *manager = [CLLocationManager updateManagerWithAccuracy:50.0 locationAge:15.0  authorizationDesciption:CLLocationUpdateAuthorizationDescriptionAlways]; 
    [self.manager startUpdatingLocationWithUpdateBlock:^(CLLocationManager *manager, CLLocation *location, NSError *error, BOOL *stopUpdating) { 
    self.mapView.camera = GMSCameraPosition.camera(withTarget: location.coordinate, zoom: 14) 
}]; 

如果你不」想要使用上述助手代碼,那麼你可以得到用戶的位置using Core Location basic api爲好。

請注意,每次更改用戶位置時,您的代碼都會調用observeValue,導致爲用戶的位置圖設置相機。

相關問題