2012-12-05 40 views
0

我想使用實際位置座標(CLLocationManager)來反向地理編碼(CLGeoCoder)。 我有這樣的代碼:CLLocationManager和CLGeoCoder

 locationMgr = new CLLocationManager(); 
     locationMgr.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; 
     locationMgr.DistanceFilter = 10; 
     locationMgr.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => { 
      Task.latitude = e.NewLocation.Coordinate.Latitude; 
      Task.longitude = e.NewLocation.Coordinate.Longitude; 
      locationMgr.StopUpdatingLocation(); 
     }; 

     btnLocation = new UIBarButtonItem(UIImage.FromFile("Icons/no-gps.png"), UIBarButtonItemStyle.Plain, (s,e) => { 
      if (CLLocationManager.LocationServicesEnabled) { 
        locationMgr.StartUpdatingLocation(); 

        geoCoder = new CLGeocoder(); 
        geoCoder.ReverseGeocodeLocation(new CLLocation(Task.latitude, Task.longitude), (CLPlacemark[] place, NSError error) => { 
         adr = place[0].Name+"\n"+place[0].Locality+"\n"+place[0].Country; 
         Utils.ShowAlert(XmlParse.LocalText("Poloha"), Task.latitude.ToString()+"\n"+Task.longitude.ToString()+"\n\n"+adr); 
        }); 
      } 
      else { 
       Utils.ShowAlert(XmlParse.LocalText("PolohVypnut")); 
      } 
     }); 

由於UpdatedLocation()需要幾秒鐘,ReverseGeocodeLocation的輸入()是Task.latitude = 0和Task.longitude = 0。

如何在ReverseGoecodeLocation()之前等待正確的值(Task.latitude,Task.longitude)?

感謝您的任何幫助。

+0

等到開始你的反向地理編碼查找前UpdatedLocation事件觸發。 – Jason

回答

0

您的地址解析器的ReverseGeocodeLocation方法在CLLocationManager獲取位置之前調用。

調用StartUpdatingLocation並不意味着UpdatedLocation事件將立即觸發。此外,如果您使用的是iOS 6,則永遠不會觸發UpdatedLocation。改爲使用LocationsUpdated事件。

例子:

locationManager.LocationsUpdated += (sender, args) => { 

    // Last item in the array is the latest location 
    CLLocation latestLocation = args.Locations[args.Locations.Length - 1]; 
    geoCoder = new CLGeocoder(); 
    geoCoder.ReverseGeocodeLocation(latestLocation, (pl, er) => { 

     // Read placemarks here 

    }); 

}; 
locationManager.StartUpdatingLocation();