繁体   English   中英

如何在Android中获取当前位置的经度和纬度

[英]How to get latitude and longitude of current location in Android

我正在尝试使用以下方法获取当前位置的纬度和经度:

 GoogleMap map;
 map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
 map.setMyLocationEnabled(true);

 lat = map.getMyLocation().getLatitude();
 lng = map.getMyLocation().getLongitude();

由于某种原因,最后两行由于NullPointerException而导致应用程序崩溃。 我究竟做错了什么?

令我感到map.setMyLocationEnabled(true);的最大事情是map.setMyLocationEnabled(true); 确实设置了我当前的位置。

多亏有人在看这个

尝试这个:

public Double Lat = null;
public Double Lng = null;
String LatLng = null;
private LocationClient mLocationClient;

在您的onCreateView()中添加此

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.yourLayout, container, false);
        mLocationClient = new LocationClient(getActivity(), this, this);

rootView.findViewById(R.id.ATestButton).setOnClickListener(
        // Get the current location
                Location currentLocation = mLocationClient.getLastLocation();
                Lat = currentLocation.getLatitude();
                Lng = currentLocation.getLongitude();
                LatLng = Double.toString(Lat) + "," + Double.toString(Lng);
                Toast.makeText(getActivity(), LatLng, 0).show();
                });

查看我完整的github上的工作示例。

//我需要一个测试按钮,因此可以单击它以查看是否返回了任何内容。

map.getMyLocation()为null,应检查该条件

您的应用崩溃是因为

map.getMyLocation() 

如果没有可用的位置数据,则返回null。因此,您可以进行!= null检查,如下所示

if( map.getMyLocation() !=null){
  lat = map.getMyLocation().getLatitude();
  lng = map.getMyLocation().getLongitude();
}

另外,不建议使用此方法,因此应改为使用FusedLocationProviderApi 在这里查看官方文档

是FusedLocation Api的一个很好的实现,您也可以检查一下。

    public void turnGPSOn() {

        String provider = Settings.Secure.getString(getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if (!provider.contains("gps")) {
            final Intent poke = new Intent();
            poke.setClassName("com.android.settings",
                    "com.android.settings.widget.SettingsAppWidgetProvider");
            poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
            poke.setData(Uri.parse("3"));
            sendBroadcast(poke);
        }
    }


void getLocation()
{
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    if (!locManager
                            .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        turnGPSOn();
                    }

                    try {
                        locManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER, 1000, 10,
                                locationListener);

                    } catch (Exception ex) {

                    }

                }


}
private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

private void updateWithNewLocation(Location location) {
        String latLongString = "";
        try {
            if (location != null) {

                Log.e("test", "gps is on send");
                latitude = Double.toString(location.getLatitude());
                longitude = Double.toString(location.getLongitude());


                Log.e("test", "location send");


                latLongString = "Lat:" + latitude + "\nLong:" + longitude;
                Log.w("CurrentLocLatLong", latLongString);
            } else {
                latLongString = "No location found";
            }
        } catch (Exception e) {
        }

    }

我找到了解决方案。 虽然我仍然不确定为什么其他方法会给我一个空指针,但是下面的方法可以很好地满足我的需求。

 LocationManager locman = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
 Location location = locman .getLastKnownLocation(LocationManager.GPS_PROVIDER);
 double lng = location.getLongitude();
 double lat = location.getLatitude();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM