gpt4 book ai didi

java - 在 Android Google Map API 中的 onMayReady() 处获取初始坐标

转载 作者:行者123 更新时间:2023-12-01 19:23:32 24 4
gpt4 key购买 nike

我正在实现 Google map API,其中我尝试在 onMapReady() 处获取初始位置。

mCurrentLocation 应该是存储位置的变量,因此我尝试在 onMapReady() 中的日志中输出该变量,但在开始时 mCurrentLocation > 为 null,所以首先我必须请求一个位置。我对api不熟悉。我做了一个猜测,并将 startLocationUpdates(this) 放在前面。

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);

LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 14.0f));

// Start the update??
startLocationUpdates(this);
// This is where I want to retrieve the location coordinates
Log.w("Location", "Current reading: " + mCurrentLocation.toString());
}

没成功。在堆栈跟踪中,它显示java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.String android.location.Location.toString()”。我还尝试了其他方法,例如 initLocation(),但它也不起作用。

这是代码的其余部分:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initLocations();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case ACCESS_FINE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, null /* Looper */);
}
return;
}
}
}

private void initLocations() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION);
}
return;
}
}

private void startLocationUpdates(Context context) {
Intent intent = new Intent(context, LocationService.class);
mLocationPendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Task<Void> locationTask = mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationPendingIntent);
if (locationTask != null) {
locationTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
if (e instanceof ApiException) {
Log.w("Main2Activity", ((ApiException) e).getStatusMessage());
} else {
Log.w("Main2Activity", e.getMessage());
}
}
});

locationTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Log.d("Main2Activity", "restarting gps successful!");
}
});


}
}
}

private void stopLocationUpdates(){
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}

@Override
protected void onResume() {
super.onResume();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
accelerometer.startAccelerometerRecording();

}

private Location mCurrentLocation;
private String mLastUpdateTime;
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrentLocation = locationResult.getLastLocation();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i("MAP", "new location " + mCurrentLocation.toString());
if (mMap != null)
mMap.addMarker(new MarkerOptions().position(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()))
.title(mLastUpdateTime));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), 14.0f));
}
};

请求位置的正确方法是什么?

最佳答案

我总是使用 LocationManager 来获取当前位置,并确保您当前的 GPS 已打开。

final LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// this is where you get the location location.getLatitude(), location.getLongitude()
}

@Override public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override public void onProviderEnabled(String provider) { }
@Override public void onProviderDisabled(String provider) { }
}, null);

关于java - 在 Android Google Map API 中的 onMayReady() 处获取初始坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59332473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com