Search code examples
androidgoogle-mapsandroid-gps

android -LocationManager return 0.0 for latitude and longitude


I want to get current latitude and longitude when user clicks on a button . to do so ,I've written these codes :

LocationManager mlocManager=null;
                        LocationListener mlocListener;
                        mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                        mlocListener = new MyLocationListener();
                        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
                        if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                            Log.v("this",MyLocationListener.latitude+ " lat");
                            if(MyLocationListener.latitude>0){
                                in = new Intent(DrawerActivity.this, Barbers.class);
                                in.putExtra("w", "nearest");
                                in.putExtra("latitude",Double.toString(MyLocationListener.latitude));
                                in.putExtra("longitude",Double.toString(MyLocationListener.longitude));
                                startActivity(in);
                            }else{
                                MyToast.makeText(DrawerActivity.this, Z_Farsi.Convert(getString(R.string.gpsfinding)));
                            }
                        } else {
                            MyToast.makeText(DrawerActivity.this, Z_Farsi.Convert(getString(R.string.gpsoffline)));
                        }

The gps is on and the current location is showing on google map perfectly .

What is the problem ? why it returns 0.0 ?

how to solve this ?


Solution

  • getLastKnownLocation is missing. You should have something like this :

    Location location = null;
    if (mlocManager!= null) {
                        location = mlocManager
                             .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }