在我的应用中,我试图在登录时获取用户当前的纬度和经度值。但问题是有时我得到空值,有时甚至是0.0作为值。我甚至去了通过堆栈溢出的类似帖子,但无法获得解决方案。请帮助。 这是我的GPSTracker.java服务类
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
alertDialog.setCancelable(false);
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location)
{
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
答案 0 :(得分:1)
获得null或(0.0,0。)坐标有多种原因。
尽管存在有效的(0.0,0.0)坐标,但实际上它从来都不是有效的,或者设计成表示无效位置的方式。
因此,您可以安全地忽略所有null和(0.0,0.0)位置。
阅读API如何确定交付的位置是否有效! 在iOS中,只有在horicontalAccuracy> = 0时才有效 来自Andorid位置文件:
“LocationManager生成的所有位置都保证有 有效的纬度,经度和时间戳(UTC时间和已过去时间) 实时启动后),所有其他参数都是可选的。 “
所以你描述的情况不应该发生。 因此,只需忽略那些(0,0)位置!
进一步修改您的应用:首次初始化后,您应该获取最后一个已知位置,然后使用OnLocationChanged
()获取更多位置更新。
答案 1 :(得分:0)
您将获得OnLocationChanged()方法
中的当前位置@Override
public void onLocationChanged(Location location)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
}
答案 2 :(得分:0)
使用此方法
public class DashActivity extends ActionBarActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
LatLng secondToLastLocation;
LocationClient mLocationClient;
double latitudeValue, longitudeValue;
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// Update frequency in milliseconds
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash);
mLocationClient = new LocationClient(this, this, this);
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority( LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
}
public double getLongitude() {
return mLocationClient.getLastLocation().getLongitude();
}
public double getLatitude() {
return mLocationClient.getLastLocation().getLatitude();
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(this, "Connetion fail, Unable to detect location", Toast.LENGTH_LONG).show();
}
@Override
public void onConnected(Bundle arg0) {
Toast.makeText(this, "Connected, dectecting location", Toast.LENGTH_LONG).show();
mLocationClient.requestLocationUpdates(mLocationRequest, this);
sendToServer();
}
@Override
public void onDisconnected() {
Toast.makeText(this, "You are disconnected", Toast.LENGTH_LONG).show();
timer.interrupt();
}
@Override
protected void onStop() {
// Disconnecting the client invalidates it.
mLocationClient.disconnect();
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
@Override
public void onLocationChanged(Location location) {
// assign some stuff here when location chaneges
}
}
首先从方法getLongitude()
和getLongitude()
获取最后一个知道位置,然后当位置发生变化时,您可以从onLocationChange()
知道位置事件的比率检测第一组行中写入的变化。您需要先从设备中获取上次保存的位置,它才能脱机工作