繁体   English   中英

单击按钮后,如何使用“用户当前位置”显示注释?

[英]How do I display an annotation using the Users current location when a button is clicked?

因此,我正在创建一个应用程序,当单击按钮时,将使用用户当前位置在Apples mapkit上创建注释。 除了将按钮链接到将创建注释并在地图上显示注释的代码之外,我已经完成了所有工作。 贝娄是我到目前为止的代码:

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {

var locationManager = CLLocationManager()

@IBOutlet var Map: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {

    println("Updating Location \(newLocation.coordinate.latitude) , \(newLocation.coordinate.longitude) ")

    let span = MKCoordinateSpanMake(0.0009, 0.0009)
    let region = MKCoordinateRegion(center: newLocation.coordinate, span: span)
    Map.setRegion(region, animated: false)
    }
}

如您所见,我拥有它,因此它不断向用户显示他们的位置。 我想要这个,但是我也希望用户能够创建注释。

我的问题是创建注释需要什么代码,它在哪里? 我是编程的新手,所以我对所有的代码术语并不完全了解,所以请(对我来说愚蠢的东西)。 同样,当用户单击添加注释的按钮时,需要删除最后一个注释。 我该怎么做? 我在Xcode中使用Swift。

你快到了!

  • 首先,在代码顶部(在类内)创建一个注释:

    var annotation = MKPointAnnotation()

  • 然后,使用newLocation.coordinate.latitude.longitude创建一个CLLocationCoordinate2D并将其设置为annotation.coordinate .longitude

    • 然后使用map.title = "something"map.addAnnotation(annotation)

    • 您需要使某些变量具有全局性才能实现此目的,但是在放置注释之前,只需使用map.removeAnnotation(annotation) -这样您一次只能在屏幕上拥有一个注释。

暂无
暂无

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

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