我正在使用谷歌地图来获取我的当前位置,并在我的位置上显示一个红色标记。到目前为止,只有mMap.setMyLocation(true);
适用于我的位置。我在代码末尾userLocation
的对象获得了 NullPointerException,并且userLocation
控制台的输出也是空的。
如何在加载地图后立即设置用户位置?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
LatLng userLocation;
private FusedLocationProviderClient mFusedLocationClient;
public float DEFAULT_ZOOM = 15f;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
System.out.println("the latitude onLocationChanged is "+ userLocation.latitude);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);
// LatLng latLng = new LatLng(40.741895,-73.989308);
mMap.setMyLocationEnabled(true);
//outputs the latitude is null
System.out.println("the latitude is "+userLocation);
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
}
}
}
你不能。 获取位置需要时间。 在调用回调之前,它不可用,这意味着在此之前您无法加载它。 您可以尝试调用getLastKnownLocation,但它在大多数情况下也会返回null。 最好的解决方案是在进行回调之前不要依赖它。
on method, OnMapReady 使用此代码
if (!mMap.isMyLocationEnabled())
mMap.setMyLocationEnabled(true);
Location userLocation = getLocation();
如果需要,请使用此方法获取最后一个位置
public Location getLocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation == null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String provider = lm.getBestProvider(criteria, true);
myLocation = lm.getLastKnownLocation(provider);
}
return myLocation;
}
注意:GPS_PROVIDER
在室内不起作用,因此您应该在室外尝试。
也许你想开始回调只是在最后一个位置之前超过一分钟。 使用此代码
if (System.currentTimeMillis()-myLocation.getTime()>60000){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);
};