【问题标题】:Latitude and longitude values are giving null values , 0.0纬度和经度值给出空值,0.0
【发布时间】:2015-09-18 11:26:09
【问题描述】:

在我的应用程序中,我试图在登录时获取用户当前的纬度和经度值。但问题是有时我得到空值,有时甚至 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;
    }

}

【问题讨论】:

    标签: android gps latitude-longitude


    【解决方案1】:

    获取 null 或 (0.0, 0.) 坐标有多种原因。 尽管存在一个有效的 (0.0, 0.0) 坐标,但实际上它从来都不是一个有效的坐标,或者以这种方式设计来表达无效的位置。
    因此,您可以放心地忽略所有 null 和 (0.0, 0.0) 位置。

    阅读API如何确定一个交付的位置是否有效! 在 iOS 中,仅当 horicontalAccuracy >= 0 时才有效。
    来自 Andorid 位置文档:

    "LocationManager 生成的所有位置都保证有 有效的纬度、经度和时间戳(UTC 时间和经过的时间) 自启动后实时),所有其他参数都是可选的。 "

    所以你描述的情况不应该发生。 因此,只需忽略 (0,0) 个位置!

    进一步修改您的应用程序:首先在初始化后您应该获取最后一个已知位置,然后使用OnLocationChanged() 获取进一步的位置更新。

    【讨论】:

      【解决方案2】:

      您将在 OnLocationChanged() 方法中获取当前位置

      @Override
      public void onLocationChanged(Location location)
      {
            double lat = location.getLatitude();
            double lon = location.getLongitude();
      }
      

      【讨论】:

      • 您在 onLocationChanged 中获得了哪些值。如果您的位置更新,它将被调用
      【解决方案3】:

      使用这个方法

      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() 中知道位置事件检测到书面变化的速率第一组线。您需要先从设备中获取最后保存的位置,它可以离线使用

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 2016-09-15
        • 1970-01-01
        相关资源
        最近更新 更多