MonoTouch:获取经度和经度值崩溃

时间:2013-06-03 20:33:47

标签: xamarin.ios cllocationmanager latitude-longitude

在我的应用中,我想获得纬度和经度值。我有以下代码。第一次调用函数时它会崩溃。应用程序要求用户使用当前位置和应用程序崩溃的权限,抛出空引用异常,我将纬度值分配给字符串

string getLocation()
{
   string latlong = "|";

   CLLocationManager locationManager = new CLLocationManager();

   locationManager.StartUpdatingLocation();

   //var locationVar = locationManager.Location.Coordinate;

   string lat = locationManager.Location.Coordinate.Latitude.ToString();
   string lon = locationManager.Location.Coordinate.Longitude.ToString();
   latlong = lat + "|" + lon;


   return latlong;
}

1 个答案:

答案 0 :(得分:4)

在检索到位置之前,您无法从locationManager检索位置。您需要指定在找到位置时调用的事件处理程序。

Xamarin的CoreLocation sample包含了如何执行此操作的完整示例

// handle the updated location method and update the UI
if (UIDevice.CurrentDevice.CheckSystemVersion (6, 0)) {
  iPhoneLocationManager.LocationsUpdated += (object sender, CLLocationsUpdatedEventArgs e) => {
    UpdateLocation (mainScreen, e.Locations [e.Locations.Length - 1]);
  };
} else {
  // this won't be called on iOS 6 (deprecated)
  iPhoneLocationManager.UpdatedLocation += (object sender, CLLocationUpdatedEventArgs e) => {
    UpdateLocation (mainScreen, e.NewLocation);
  };
}