纬度经度未出现

时间:2018-05-17 14:46:16

标签: android location latitude-longitude

我有以下功能来检索手机当前位置的纬度和经度。

  private void getLocation() {


    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
            (MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

    } else {

        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);


        if (location != null) {
            double latti = location.getLatitude();
            double longi = location.getLongitude();
            lattitude = String.valueOf(latti);
            longitude = String.valueOf(longi);

            textView.setText("Your current location is" + "\n" + "Lattitude = " + lattitude
                    + "\n" + "Longitude = " + longitude);

        } else {

            Toast.makeText(this, "Unable to Trace your location", Toast.LENGTH_SHORT).show();
        }
    }

}

通过按钮调用此功能。问题是,通过单击按钮,该功能似乎找不到位置,并继续烘烤在else语句中烘烤的相同消息。有人可以指出我做错了什么。

1 个答案:

答案 0 :(得分:0)

首先,您需要定义LocationListener

private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
    //your code here to get lat lon from location
}

在活动中

mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
        LOCATION_REFRESH_DISTANCE, mLocationListener);