【问题标题】:MonoTouch: Get latitude and longitude values crashesMonoTouch:获取纬度和经度值崩溃
【发布时间】:2013-05-30 02:42:44
【问题描述】:

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

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

【问题讨论】:

    标签: xamarin.ios cllocationmanager latitude-longitude


    【解决方案1】:

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

    【讨论】:

    • 只是一个小问题,UpdateLocation 函数被多次调用。是这样的吗。在我的应用中,我不想多次调用它。
    • 如果您的手机在移动,GPS 会随着位置的变化而更新。当您想停止获取更新时,请调用 StopUpdatingLocation()。
    • 我第一次调用 UpdateLocation 时会被多次调用。在我的代码中,当我得到 lat、long 值时,我会停止更新(StopUpdatingLocation),但最终还是会多次给我 lat/long 值。
    • GPS 返回值的速度可能比您响应它们的速度快。如果您只想要第一个值,只需使用 bool 来跟踪您是否获得了第一个更新。设置后,忽略任何未来的更新,同时调用 StopUpdatingLocation()
    猜你喜欢
    • 1970-01-01
    • 2019-03-25
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多