标记当前位置不断给出坐标 0,0

Marking current locations keeps giving the coordinates 0,0

我正在为我使用 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()
}

它将 return 0 因为您创建了一个新的 CLLocation() 实例,其中没有任何内容。 从 locationManager(_:didUpdateLocations:) 委托获取当前位置。

这样做:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    userLocation = locations.last
}

并从您的 markCurrentLocation(_:) 方法中删除 let userLocation = CLLocation()

另外请务必在您的 info.plist 中添加请求