【问题标题】:Android get Location doesnt work properlyAndroid获取位置无法正常工作
【发布时间】:2013-04-22 00:01:24
【问题描述】:

我正在尝试获取位置并且代码可以正常工作,但无法正常工作。这是我的代码

    // Get the location manager
    LocationManager locationManager = (LocationManager)                 
    getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String bestProvider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(bestProvider);

    try {
        lat =  (int)Math.round((location.getLatitude () * 1e6) ) ;
        lon =   (int)Math.round((location.getLongitude() * 1e6) ) ;
    }
    catch (NullPointerException e){
        lat = -1;
        lon = -1;
    }

问题是当我使用foursqure 或facebook 时,他们直接获取位置,但我的应用程序返回-1,-1(有时),有时它会准确找到位置。可能是什么问题,或者我该如何改进以更好地获得当前位置?谢谢

【问题讨论】:

    标签: android gps location locationmanager


    【解决方案1】:

    您应该实现 LocationListerner 并请求位置更新。获得修复后,您可以删除位置更新。你可以在http://developer.android.com/reference/android/location/LocationListener.html阅读更多信息

    【讨论】:

      【解决方案2】:

      对 getLastKnownLocation 的调用有时会返回 null,如 Andorid documentation 中所指定。所以有时该代码确实会产生 lat=lon=-1。此外,getBestProvider 是一种确定最能满足给定标准的提供者的方法。由于您没有指定任何标准,因此合乎逻辑的结论是所有提供者都同样出色,因此结果可能是随机的。最后,请注意 lat=-1 和 lon=-1 是一个有效的位置,因此通常它不是标记错误的好方法。

      正如此处另一个答案中所建议的,您应该实施 http://developer.android.com/reference/android/location/LocationListener.html 。然后,您遇到了使用哪些提供程序的问题。我的方法是全部使用它们并使用一个简单的卡尔曼滤波器来处理不同提供者在不同时间具有不同准确度的事实。我在这里发布了我用于此的简单卡尔曼滤波器Smooth GPS data

      【讨论】: