我想获得latitude
和longitude
但有时network is available
,但我没有获得latitude
和longitude
的价值。我正在使用 MyLocationListener 类并将条件设置为value
没有得到的所有时间。
protected void showCurrentLocation()
{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
}
private class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location location)
{
counter++;
latitude=location.getLatitude();
longitude=location.getLongitude();
altitude=location.getAltitude();
}
@Override
public void onStatusChanged(String s, int i, Bundle b)
{
}
@Override
public void onProviderDisabled(String s)
{
}
@Override
public void onProviderEnabled(String s)
{
}
}
答案 0 :(得分:5)
获取经度纬度的最佳方式:
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "changed Loc : "+longitude + ":"+latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if(isGPSEnabled){
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d("msg", "Loc : "+longitude + ":"+latitude);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}else
{
/*
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);
String provider = locationManager.getBestProvider(criteria, true);
*/
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}else
{
longitude = "0.00";
latitude = "0.00";
}
}
}
如果设备无法使用GPS
获取currentLocation,那么它将从NetworkProvider
开始,否则它将以0,0作为我的要求,但您可以根据您的要求进行修改< / p>
愿它对你有所帮助。
快乐编码:D
答案 1 :(得分:0)
看,这是一个非常常见的问题。为了获得精确的纬度和经度,您必须使用GPS,它必须在移动设备上激活,但GPS也有一些限制。 GPS在开阔的天空下工作效率最高。你不会在建筑物内有明确的范围。所以在开放的天空下尝试你的代码并检查响应。