2017-06-14 20 views
0

我試圖將座標存儲在數組中。代碼運行良好,但是在每次迭代新實現的座標之後,數組數仍然保持不變?插入時未存儲在數組中的座標

let manager = CLLocationManager() 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let location = locations[0] 
    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01,0.01) //shows the size of map screen 
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude) 
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span) 
    map.setRegion(region, animated: true) 
    self.map.showsUserLocation = true 
    let LAT = Double(location.coordinate.latitude) 
    let LONG = Double(location.coordinate.longitude) 
    var locationArray = [Double]() 
    locationArray.insert(contentsOf: [LAT, LONG], at: 0) 
    print(locationArray.count) 

回答

0

發生這種情況是因爲您正在每次迭代中創建一個新的locationArray。您需要聲明位於更新範圍之外的locationArray,在此處插入座標。

var locationArray = [Double]() 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    let location = locations[0] 
    let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01,0.01) //shows the size of map screen 
    let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude) 
    let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span) 
    map.setRegion(region, animated: true) 
    self.map.showsUserLocation = true 
    let LAT = Double(location.coordinate.latitude) 
    let LONG = Double(location.coordinate.longitude) 
    locationArray.insert(contentsOf: [LAT, LONG], at: 0) 
    print(locationArray.count) 
} 
+1

工作馬上,謝謝! –