User382
User382

Reputation: 874

MonoTouch: Get latitude and longitude values crashes

In my app i want to get the latitude and longitude values. I have below code. It crashes very first time the function get called. App asks the user permission to use current location and app crashes throwing null reference exception where i am assigning latitude value to a string

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

Upvotes: 1

Views: 1277

Answers (1)

Jason
Jason

Reputation: 89129

You cannot retrieve the location from locationManager until it has retrieved a location. You need to assign an event handler that will be called when the location is found.

The CoreLocation sample from Xamarin includes a complete example of how to do this

// 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);
  };
}

Upvotes: 4

Related Questions