2016-10-25 13 views
1

CLLocationManagerを使用して移動距離を計算し、ラベル内の距離を表示しようとしています。場所の使用を要求しても、ラベルには何も表示されません。私はxCodeシミュレータの中でドライブをシミュレートしようとしましたが、無駄です。私は地図がアプリケーションの中に表示され、それは動作し、それは私の場所を追跡しますが、それはすべて動作します。スウィフト3で距離が計算されていません

は、相続人は私のlocationManager方法:

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

    // Map 

    theLabel.text = "\(locations[0])" 
    myLocations.append(locations[0] as! CLLocation) 

    let spanX = 0.007 
    let spanY = 0.007 
    let newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY)) 
    theMap.setRegion(newRegion, animated: true) 

    if (myLocations.count > 1){ 
     let sourceIndex = myLocations.count - 1 
     let destinationIndex = myLocations.count - 2 

     let c1 = myLocations[sourceIndex].coordinate 
     let c2 = myLocations[destinationIndex].coordinate 
     var a = [c1, c2] 
     let polyline = MKPolyline(coordinates: &a, count: a.count) 
     theMap.add(polyline) 
    } 

    // Labels 

    let latestLocation: AnyObject = locations[locations.count - 1] 
    lat.text = String(format: "%.4f", latestLocation.coordinate.latitude) 
    long.text = String(format: "%.4f", latestLocation.coordinate.longitude) 
    horizAcc.text = String(format: "%.4f", latestLocation.horizontalAccuracy) 
    altitude.text = String(format: "%.4f", latestLocation.altitude) 
    vertAcc.text = String(format: "%.4f", latestLocation.verticalAccuracy) 

    if startLocation == nil { 
     startLocation = latestLocation as! CLLocation 
    } 

    let distanceBetween = (latestLocation.distance(from: startLocation)) 

    distance.text = String(format: "%.2f", distanceBetween) 

} 

すべてのヘルプは大歓迎です!必要に応じてより多くのコードを提供することができます。

+0

正確に動作していないものを教えてください。 "それはすべて働いている"と広義になります – alexburtnik

+0

私は距離を計算してラベルに入れていますが、ラベルは決して変化しません。 –

+0

最後に 'print(distanceBetween)'を実行して出力を教えてください –

答えて

0

CLLocationManagerのインスタンスに対してデリゲートプロパティが正しく設定されていないようです。どのオブジェクトに、リストされたメソッドのようなCLLocationManagerDelegateメソッドの実装が含まれているかを知らせる必要があります。

だから、あなたのビューコントローラを仮定すると、CLLocationManagerDelegateに準拠しており、あなたが投稿メソッドが含まれていると、あなたのビューコントローラ「locationManager」と呼ばれるCLLocationManagerプロパティを与えていると仮定すると、あなたは、単にこのようにそれを設定します。

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

ますそれをviewDidLoad:に置くか、あなたの必要に応じてどこにでも置くことができ、didUpdateLocationデリゲートメソッドを呼び出す必要があります。

関連する問題