gpt4 book ai didi

ios - 从当前位置添加注释

转载 作者:可可西里 更新时间:2023-11-01 01:37:33 25 4
gpt4 key购买 nike

我想在点击按钮时从用户位置添加注释。我猜它快要工作了,但是当我点击按钮时,它会在非洲的某个地方添加注释。 (纬度:0,经度:0)。为什么它不显示正确的用户位置?

导入 UIKit导入 MapKit导入核心位置

类 ViewController:UIViewController,CLLocationManagerDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()

}

@IBAction func addAnnotation(sender: UIBarButtonItem) {

let addPin = MKPointAnnotation()
addPin.coordinate = CLLocationCoordinate2D(latitude: self.mapView.userLocation.coordinate.latitude, longitude: self.mapView.userLocation.coordinate.longitude)
addPin.title = "Hello world"
mapView.addAnnotation(addPin)

}

最佳答案

您遇到的问题是您没有获取用户的位置信息。您需要在代码中添加一些内容才能实现此目的。我已经添加了整个代码,请查看评论中的描述。

import CoreLocation
import MapKit
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet var mapView: MKMapView!
var locationManager = CLLocationManager()
// Add two variables to store lat and long
var lat = 0.0
var long = 0.0

override func viewDidLoad() {
super.viewDidLoad()
// Check if you have the right to get the location
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}

override func viewWillAppear(animated: Bool) {
// Start get the location on viewWillAppear
locationManager.startUpdatingLocation()
}

@IBAction func addAnnoation(sender: AnyObject) {
locationManager.startUpdatingLocation()
let annotation = MKPointAnnotation()
// Set the annotation by the lat and long variables
annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
annotation.title = "User location"
self.mapView.addAnnotation(annotation)
}

// To get the location for the user
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocationCoordinate2D = manager.location!.coordinate
lat = location.latitude
long = location.longitude
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error")
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()


// Dispose of any resources that can be recreated.
}
}

您还需要打开您的 info.plist 文件并添加此属性: NSLocationWhenInUseUsageDescription 并添加一个字符串,说明为什么需要获取用户位置(这是强制性的,否则您将无法获取用户位置)。

关于ios - 从当前位置添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34862029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com