2015-05-06 75 views
0
import UIKit 
import MapKit 
import CoreLocation 
import Foundation 
import Darwin 

class ViewController: UIViewController, CLLocationManagerDelegate { 

let locationManager = CLLocationManager() 

var annotation = MKPointAnnotation() 

func getLocation()-> CLLocation! { 
    locationManager.startUpdatingLocation() 
    var x = locationManager.location 
    println(x.coordinate.latitude) 
    println(x.coordinate.longitude) 
    return x 

} 

我相信这个函数getLocation()是我的代码中的问题。当前位置问题

//Other variables and other actions have been set up here that are irrelevant to the problem within the code. 

var wS:CLLocationCoordinate2D! = nil 
var carParked:Bool = false 
var currentCoord:CLLocation! 

override func viewDidLoad() { 
//I have set up map, annotation, etc. in viewDidLoad and have tested that they all work perfectly fine. 
} 

@IBAction func pinButtonPressed(sender: AnyObject) { 

    carParked = true 
    var currentCoord = getLocation() 
    wS = currentCoord.coordinate 
    annotation.coordinate = wS 
    map.addAnnotation(annotation) 

    } 

    @IBAction func carFound(sender: AnyObject) { 

     carParked = false 
     map.removeAnnotation(annotation) 
     wS = nil 

} 

其中这两个按钮,pinButtonPressed或carFound将是错误的第二个最有可能的地方。

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

我想要什么的代码做的是,每当按下pinButtonPressed被标注将被放置在用户的当前位置和呆在那里。为了删除注释,可以按carFound按钮。然后,在第一个注释放置之后按下carFound按钮之后,应该可以再次按下pinButtonPressed,并且注释应放置在用户所在的位置,即使它们已移动。这个问题是pinButtonPressed第一次被按下,注释调用getLocation()函数,找到当前位置,并将其设置为注释坐标并放置注释,然后使用carFound移除注释;然后,我移动当前位置并再次按下pinButtonPressed函数,并将注释放置在原来的时间位置,而不是移动到的位置。我已经放置了两条打印线来打印getLocation()函数返回的坐标,并且这些坐标始终与自模拟开始运行后检索到的第一个坐标相同,无论我将当前位置移动到哪里并按下pinButtonPressed按钮。我相信我忽略了一些显而易见的东西,并想知道是否有人有任何想法可以帮助。谢谢。

回答

0

您必须使用位置管理器的代理(CLLocationManagerDelegate)方法。使用方法:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {} 

在此您应该更新位置。