简体   繁体   English

如何使用CoreLocation在当前位置添加注释

[英]How to Add an annotation At your current location using CoreLocation

I have everything working except the actual button function code. 除了实际的按钮功能代码之外,我所有的工作都可以进行。 Here is My code but it does not add an annotation. 这是我的代码,但未添加注释。

@IBAction func AddAnnotation(_ sender: UIButton) {
        CLLocationManager().startUpdatingLocation()
        let annotation = MKPointAnnotation()
        // Set the annotation by the lat and long variables
        annotation.coordinate = CLLocationCoordinate2D()
        annotation.title = "My Car"
        self.map.addAnnotation(annotation)
    }

Your code can't possibly work. 您的代码可能无法正常工作。 When you call startUpdatingLocation() , it takes several seconds for the GPS to start up and get an accurate fix. 当您调用startUpdatingLocation() ,GPS会花费几秒钟来启动并获得准确的定位。 you have to set yourself up as it's delegate, and then wait for your locationManager(_:didUpdateLocations:) method to be called. 您必须将自己设置为委托,然后等待您的locationManager(_:didUpdateLocations:)方法被调用。

You'd put your code to add an annotation in that method. 您需要将代码放入该方法中添加注释。

As others have said, you also need to write code that checks to see if you are authorized to get the user's location, and ask permission if not. 正如其他人所说,您还需要编写代码以检查您是否被授权获取用户的位置,如果没有,则请求权限。 (And You'll need to add a special key to your app's info.plist file indicating that your app needs access to the user's location.) (并且,您需要在应用的info.plist文件中添加一个特殊键,以指示您的应用需要访问用户的位置。)

Take a look at the documentation on Core Location and using the location Manager in Xcode, and you might want to find a tutorial that walks you through the steps. 查看有关Core Location的文档,并在Xcode中使用location Manager,您可能想要找到一个指导您完成这些步骤的教程。 It's a little involved. 这有点涉及。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM