我需要以编程方式在Android中获取经度和纬度的正确方法。我查看了不同的网站和论坛,但仍然无法得到正确的网站和论坛。该程序应支持所有Android版本。我使用wifi将我的设备连接到网络。
答案 0 :(得分:0)
下面的实现创建了一个locationlistener,它将更新后的值记录为字符串,以方便提取。通过使用LocationManager,您可以抽象底层方法(GPS / assissted-GPS,wifi,cell-tower)来检索位置。
首先初始化:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
final myLocationListner ll = new myLocationListner();
LocationListener的:
public class myLocationListner implements LocationListener {
public static String lattitude = "";
public static String longitude = "";
@Override
public void onLocationChanged(Location loc) {
String temp_lattitude = String.valueOf(loc.getLatitude());
String temp_longitude = String.valueOf(loc.getLongitude());
if(!("").equals(temp_lattitude))lattitude = temp_lattitude;
if(!("").equals(temp_longitude))longitude = temp_longitude;
}
@Override
public void onProviderDisabled(String arg0) {
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
答案 1 :(得分:0)
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.length();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;}