【发布时间】:2011-07-27 15:59:21
【问题描述】:
我的代码在给定时间获取某个位置的坐标,然后显示纬度/经度坐标。我认为我的代码是正确的,但问题在于向手机授予 GPS 权限。我使用的是三星 Nexus S,并且安装了所有正确的驱动程序,但手机上没有网络。有人告诉我 GPS 应该仍然可以工作并且应该能够检索坐标。我已启用“使用 GPS 卫星”设置,并已在清单中授予权限,如 manifest.xml 中所示
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
我提供了所有可能的位置权限,以防我遗漏了什么,希望这不是问题。
至于我的代码,我在 onCreate 方法中有这个(类?我不确定它的正确名称)
double[] gps = getGPS();
TextView tv = (TextView) this.findViewById(R.id.gpsCoordinates);
tv.setText("Latitude: " + gps[0] + "\nLongitude: " + gps[1]);
然后是 GPS 类中的私有方法来实际获取坐标
private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
我相信我从 stackoverflow 和其他一些论坛中提取了这段代码,然后对其进行了一些调整。
【问题讨论】:
-
如果您可以在手机上安装类似谷歌地图应用程序的东西,它可能会修复设置中的任何错误并让 GPS 正常工作。
-
我安装了 Google 地图,但它显示“网络故障 - 此应用程序需要有效的数据连接”
标签: android gps coordinates