Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android-LocationManager返回0.0表示纬度和经度_Android_Google Maps_Android Gps - Fatal编程技术网

android-LocationManager返回0.0表示纬度和经度

android-LocationManager返回0.0表示纬度和经度,android,google-maps,android-gps,Android,Google Maps,Android Gps,我想在用户单击按钮时获取当前纬度和经度。为此,我编写了以下代码: LocationManager mlocManager=null; LocationListener mlocListener; mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); mlocL

我想在用户单击按钮时获取当前纬度和经度。为此,我编写了以下代码:

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)));
                        }
gps已打开,当前位置在谷歌地图上完美显示

有什么问题?为什么它返回0.0


如何解决这个问题

缺少getLastKnownLocation

。你应该有这样的东西:

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

manager.requestLocationUpdates("gps", 10, 10, new LocationListener() {
@Override
public void onLocationChanged(Location location) {

 double lat=location.getLatitude();
 double lon=location.getLognitude()

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
});

这个文件将为您完成这项工作。它将从网络运营商或GPS获取数据

GPSTracker.java

public class GpsTracker extends Service implements LocationListener {

    private final Context mContext;

    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;
    double latitude;
    double longitude;

    private final long MIN_DISTANCE = 10;
    private final long MIN_TIME = 30;
    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 enabled
            } else {

                this.canGetLocation = true;

                // first get location from network provider
                if (isNetworkEnabled) {
                    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return null;
                    }
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, 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 provider

                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
                        Log.d("GPS provider", "GPS provider");

                        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) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locationManager.removeUpdates(GpsTracker.this);
        }
    }


    // functions to get latitude and longitude

    public double getLatitude()
    {
        if(location != null){
            latitude = location.getLatitude();
        }
        return latitude;
    }


    public double getLongitude()
    {
        if(location != null){
            longitude = location.getLongitude();
        }
        return longitude;
    }


    // function to check whether GPS/WiFi is enabled

    public boolean canGetLocation()
    {

        return this.canGetLocation;
    }


    /* Function to show alert dialog
     * on pressing settings button will launch settings options   */

    public void showAlertDialog()
    {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        alertDialog.setTitle("GPS Settings").setMessage("GPS not Enabled. /n Want to enable it ? ").setCancelable(false);

        alertDialog.setPositiveButton("Settings", new OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {


                // Implicit intent
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);

            }
        });

        alertDialog.setNegativeButton("No", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int arg1) {

                dialog.cancel();

            }
        });

        alertDialog.show();
    }







    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

}

我注意到,使用定位功能,您无法立即获取用户位置。您必须等待设备为您提供位置

通常,我会在我的应用程序类中包含我的代码,例如,当用户单击按钮时,您调用应用程序类中的一个方法,并让用户知道(通过进度对话框??)他们应该等待获得纬度和经度

下一步是使用事件通知活动或位置可用性片段,然后在获得数据后关闭进度对话框

只需知道,当你想立即获得当前位置时,你无法轻松获得。有时,在室内,它甚至不能像预期的那样工作


祝你好运

无论您是否尝试真正的设备和模拟器MyLocationListener的代码在哪里?您必须调用
lastKnownLocation()
方法。