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() 

} 
相关问题