我一直试图将地图集中在用户的位置上,但它一直说latLng变量为空。我已经读到发生这种情况是因为我正在使用getLastKnownLocation,但我找不到任何其他方法(我是编程新手)。我正在使用Jellybean上的谷歌api。这是我正在使用的代码。
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria,true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Latitude y longitud
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude,longitude);
//Mover el mapa a la posicion actual del usuario
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));
} else {
// Show rationale and request permission.
}
试试这个
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (bPermissionGranted) {
buildGoogleApiClient();
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
实现接口GoogleApiClient.ConnectionCallbacks
和重写方法onConnected 和 onConnectionSuspended在连接中
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(@NonNull String[] permissions, int requestCode)
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
LocationListener
接口和覆盖方法的插入
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
检查"AndroidManifest"中的权限.xml
<user-permission android:name="android.permission.ACCESS_FINE_LOCATION />
<user-permission android:name="android.permission.ACCESS_COARSE_LOCATION />
<user-permission android:name="android.permission.INTERNET />
主要是我们可以通过GPS提供商和网络提供商获取位置。如果我们通过GPS提供商获得空位置,则将提供商更改为网络。
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provideGps = locationManager.GPS_PROVIDER;
String provideNetwork = locationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(providerGps);
If (location == null) {
location = locationManager.getLastKnownLocation(providerNetwork);
location.getLatitude();
location.getLongitude();
} else {
location.getLatitude();
location.getLongitude();
}