我有一个问题,我需要像拍照一样获取特定时刻的纬度和经度。我得到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);
该按钮位于onCreateListener方法中,也位于onClickListener()按钮中。
//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) {
}
最佳答案
尝试这个:
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()方法的null值。