我正在开发一款使用Google Maps API的iPhone应用,但我在获取用户的当前位置时遇到问题,因此地图会在其位置打开。
我现在花了几天时间来解决编译器错误,但它仍然没有正常工作。地图显示,但仅在我为long和lat变量提供的初始坐标处。我认为它与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 :(得分: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()
}