1

我正在研究使用Google Maps API的iPhone應用程序,並且遇到問題獲取用戶的當前位置,以便地圖在其上打開位置。從CLLocationManager(Google Maps API)獲取用戶位置的問題

我已經花了幾天的時間了,現在已經擺脫了編譯錯誤,但它仍然不能正常工作。地圖顯示出來了,但只在初始座標處提供了長和變量變量。我認爲這與CLLoationManager()有關。

在模擬器上更新位置不會產生任何結果,我覺得我正在犯新人錯誤,我只是不知道該怎麼做。和建議?

import UIKit 
    import CoreLocation 
    import GoogleMaps 


class ViewController: UIViewController, CLLocationManagerDelegate { 

var long:Double = -0.13 
var lat:Double = 51.0 

let locationManager = CLLocationManager() 

override func loadView() { 
    // Create a GMSCameraPosition that tells the map to display the 

    //user location stuff 
    self.locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager.requestAlwaysAuthorization() 
    locationManager.startUpdatingLocation() 


    let camera = GMSCameraPosition.camera(withLatitude: CLLocationDegrees(lat), longitude: CLLocationDegrees(long), zoom: 5.0) 
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) 

    view = mapView 
    mapView.showUserLocation = true 
    // Creates a marker in the center of the map. 
    let marker = GMSMarker() 
    marker.position = CLLocationCoordinate2D(latitude: 51.51 , longitude: -0.13) 
    marker.title = "Test" 
    marker.snippet = "This is a test" 
    marker.map = mapView 
} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //i think this is the problem area 
    let userLocation = locations.last! 
    long = userLocation.coordinate.longitude 
    lat = userLocation.coordinate.latitude 

    self.locationManager.stopUpdatingLocation() 

} 
} 

回答

0

當你得到用戶的位置時,你並沒有更新地圖的當前位置。您需要執行以下操作:

// property to store map view instead of just a local variable in loadView() 
var mapView: GMSMapView? 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //i think this is the problem area 
    let userLocation = locations.last! 
    long = userLocation.coordinate.longitude 
    lat = userLocation.coordinate.latitude 

    let newCamera = GMSCameraPosition.camera(withLatitude: lat, longitude: long) 
    mapView.camera = newCamera 
    self.locationManager.stopUpdatingLocation() 

}