(Android)获取经度和纬度,始终为零

时间:2016-11-22 04:13:17

标签: java android google-maps location latitude-longitude

我有一个问题,我需要获得一个特定时刻的经度和经度,比如拍照。我得到Double值,问题是它们总是为0.我没有收到异常,并且坐标被成功上传到Firebase数据库,但是当我在JSON中检查它们时,它们总是为零(我拍了20张照片) )。

这是我的“位置”内容和上传到Firebase数据库的部分代码。

我的主要活动是这样的。

 public class MainActivity extends AppCompatActivity implements LocationListener

与位置相关的全局变量

 double latitude;
 double longitude;

这里面是onCreate():

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String networkProvider = LocationManager.NETWORK_PROVIDER;
String gpsProvider = LocationManager.GPS_PROVIDER;
final Location location= new Location(networkProvider);
onLocationChanged(location);{
     latitude=location.getLatitude();
     longitude=location.getLongitude();
}



if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
 locationManager.requestLocationUpdates(gpsProvider, 5000, 10, this);

这是一个按钮onClickListener(),也在onCreate()方法中。

//Insert coordinates to JSON Firebase database...
   Coordinates coordinates = new Coordinates();
   coordinates.setLatitude(location.getLatitude());
   coordinates.setLongitude(location.getLongitude());
   testReference.push().setValue(coordinates);
   Toast.makeText(MainActivity.this, "Coordinates uploaded!", Toast.LENGTH_LONG).show();

此外,我在MainActivity中有这些方法:

@Override
    public void onLocationChanged(Location location) {

    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

1 个答案:

答案 0 :(得分:1)

试试这个:

   locationManager = (LocationManager) getApplicationContext()
            .getSystemService(Context.LOCATION_SERVICE);


    Criteria locationCritera = new Criteria();
    String providerName = locationManager.getBestProvider(locationCritera,
            true);
    if(providerName!=null)
        location = locationManager.getLastKnownLocation(providerName);

    locationListener = new MyLocationListener();

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
            0, locationListener);

并实施您的位置监听器类:

private class MyLocationListener implements LocationListener {

public void onLocationChanged(Location loc) {

  if (loc != null) {
        location = loc; 
        latitude=location.getLatitude();
        longitude=location.getLongitude();
    }
}

public void onProviderDisabled(String provider) {

}

public void onProviderEnabled(String provider) {
}

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

}

检查getLastKnownLocation()方法的空值..