标记当前位置保持给出坐标0,0

时间:2018-03-08 00:34:43

标签: ios swift xcode core-location

我正在使用谷歌地图服务为我使用Xcode 9.2和Swift 4制作的应用程序。当我按下按钮时,我希望我的当前位置在地图视图上标记,上面有一个标记。相反,当点击按钮时,它会将我带到坐标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()
}

1 个答案:

答案 0 :(得分:2)

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

这样做:

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

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

另外请务必在info.plist中添加请求 enter image description here