【发布时间】:2018-03-08 00:34:42
【问题描述】:
我正在为使用 Xcode 9.2 和 Swift 4 制作的应用程序使用 Google 地图服务。当我按下按钮时,我希望在地图视图上标记我的当前位置,并在其上方使用标记。相反,当点击按钮时,它会将我带到坐标 0,0。我究竟做错了什么?提前感谢您的所有帮助。
//Location Manager
var userLocation = CLLocation()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations.last!
let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 14);
self.googleMapsView.camera = camera
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
//Button Marker Function
@IBAction func markCurrentLocation(_ sender: UIButton) {
let center = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
let camera = GMSCameraPosition.camera(withLatitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude, zoom: 14);
self.googleMapsView.camera = camera
self.googleMapsView.isMyLocationEnabled = true
let marker = GMSMarker(position: center)
print("Latitude :- \(userLocation.coordinate.latitude)")
print("Longitude :-\(userLocation.coordinate.longitude)")
marker.map = self.googleMapsView
marker.title = "Current Location"
googleMapsView.animate(to: camera)
//Finally stop updating location otherwise it will come again and again in this delegate
self.locationManager.stopUpdatingLocation()
}
【问题讨论】:
-
你创建了 let userLocation = CLLocation(),它是空的。相反,您应该实现 corelocation 委托方法来查明设备位置
-
请阅读Location and Maps Programming Guide 了解如何获取用户的当前位置。
-
我想你是在模拟器上测试,请启用模拟器的当前位置,或者在真机上测试。
标签: ios swift xcode core-location