1

私のアプリでは、緯度と経度の値を取得したいと考えています。以下のコードがあります。関数が呼び出されると、最初にクラッシュします。アプリが現在の場所を使用する許可をユーザーに要求し、緯度値を文字列に割り当てているところでアプリがクラッシュし、null 参照例外がスローされます

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 から場所を取得することはできません。場所が見つかったときに呼び出されるイベント ハンドラーを割り当てる必要があります。

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 に答える