1

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

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;
}
4

1 回答 1

4

在 locationManager 检索到位置之前,您无法从 locationManager 检索位置。您需要分配一个事件处理程序,当找到该位置时将调用该事件处理程序。

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

// 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);
  };
}
于 2013-06-03T20:46:37.523 回答