iOS和斯威夫特:显示距当前位置的距离? [英] iOS & Swift: display distance from current location?
问题描述
我已经检查了互连网和stackoverflow,但找不到解决我问题的方法.
I have scoured the interwebs and stackoverflow, and I can't find a solution to my problem.
我正在尝试:
- 获取用户的当前位置(经纬度)
- 计算用户当前位置与我在内部设置的另一个位置(经纬度)之间的距离
- 在列表视图中返回距离
到目前为止,如果我手动设置当前位置,但可以更新,则可以完成此操作.
So far, I can accomplish this if I manually set my current location, but I need to to update.
我已经成功返回了日志中的当前位置(我在Simulator中将其设置为Apple总部),但是在实际的应用程序或模拟器中却没有成功.
I have had success returning my current location (I set it as Apple headquarters in the Simulator) in the log, but no success in the actual app or simulator.
这就是我所拥有的:
import UIKit
import CoreLocation
import MapKit
class ViewController: UITableViewController, CLLocationManagerDelegate, MKMapViewDelegate {
override func prefersStatusBarHidden() -> Bool {
return true
}
var shops = [coffeeShop]()
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
loadShops()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
func loadShops() {
let currentLocation = CLLocation()
let currentLat = currentLocation.coordinate.latitude
let currentLong = currentLocation.coordinate.longitude
var myLocation = CLLocation(latitude: currentLat, longitude: currentLong)
let shopLocation1 = CLLocation(latitude: 39.7886939, longitude: -86.1547275)
let distance1 = myLocation.distanceFromLocation(shopLocation1) / 1000
let shop1 = coffeeShop(location: distance1)!
}
此外,我在info.plist中设置了所有内容以及所有这些好东西.
In addition, I have everything set in the info.plist and all of that good stuff.
我该怎么做!?* 轻声哭泣 *
HOW DO I MAKE THIS WORK!? * weeps softly *
在此先感谢您的帮助!
推荐答案
我能够使用以下代码来实现所需的功能.有时,您只是将其放置在宇宙中,以使宇宙自行响应.谢谢大家的帮助!
I was able to use the following code to achieve what I needed. Sometimes you just gotta put it out there in the universe for the universe to respond on its own. Thanks everyone for the help!
let currentLat = self.locationManager.location!.coordinate.latitude
let currentLong = self.locationManager.location!.coordinate.longitude
这篇关于iOS和斯威夫特:显示距当前位置的距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!