【问题标题】:Marking current locations keeps giving the coordinates 0,0标记当前位置不断给出坐标 0,0
【发布时间】: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


【解决方案1】:

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

这样做:

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

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

还要确保在 info.plist 中添加请求

【讨论】:

  • 是的,但我想在按钮的操作中使用变量,这意味着我必须在函数之外使用 'var userLocation = CLLocation()' 是否正确?
  • 可以,可以定义为全局变量。
  • 所以我这样做了,但它仍然给我坐标 0,0
  • 我刚刚更新了上面的代码......如果你不介意看看它,让我知道是否还有任何错误,那将是很棒的
  • 无需在您的按钮中调用 self.locationManager.stopUpdatingLocation()。您已经在 locationManager() 中停止了位置更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多