2015-07-13 120 views
1

所以我創建了一個應用程序,當點擊一個按鈕時,用戶當前的位置被用來在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。

回答

1

你快到了!

  • 首先,在碼(只是類內)的頂部創建註釋:

    var annotation = MKPointAnnotation()

  • 然後,使用newLocation.coordinate.latitude.longitude創建CLLocationCoordinate2D並將其設置爲annotation.coordinate

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

    • 您需要讓某些變量更具全局性才能達到此目的,但在放置註釋之前,只需使用map.removeAnnotation(annotation) - 因此您一次只能在屏幕上顯示一個註釋。

+0

好了,這裏是我的: –

+0

進口的UIKit 進口CoreLocation 進口MapKit 類的ViewController:UIViewController中,CLLocationManagerDelegate { VAR的LocationManager添加= CLLocationManager(CLLocationManager爲) //新代碼 var註解= MKPointAnnotation() // @IBOutlet var Map:MKMapView! 重寫func viewDidLoad(){ super.viewDidLoad() //在加載視圖後,通常從一個筆尖執行任何其他設置。 locationManager.delegate =自 locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() } –

+0

倍率FUNC didReceiveMemoryWarning(){ super.didReceiveMemoryWarning() //處置,可以被重新創建任何資源。 (更新位置\(newLocation.coordinate.latitude),\(newLocation.coordinate。)(位置更新位置\(newLocation.coordinate.latitude),\(newLocation.coordinate.laordinate。)(012LX} 函數locationManager(manager:CLLocationManager !, didUpdateToLocation newLocation:CLLocation !, fromLocation oldLocation:CLLocation!){ println經度)「) //新的代碼添加 newLocation.coordinate.latitude newLocation.coordinate.longitude 讓跨度= MKCoordinateSpanMake(0.0009,0.0009) –

相關問題