Android 地图我的位置层不显示 API >棉花糖



大家晚上好,

我有一个问题与谷歌地图SDK上的Android应用程序,我想显示我的位置层,我问权限FINE_LOCATION和COARSE_LOCATION在MainActivity和声明它在Manifest文件。

On APi <棉花糖,它的工作是因为,我不需要接受的权限,但与APi>=棉花糖,它是坏的。

当我启动应用程序时,我没有看到my_location_layer,我必须重新启动我的应用程序才能看到它。

下面是我的代码,如果大家能帮助我,谢谢。

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mapsexample">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MapsExample"
tools:targetApi="31">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/maps_api_key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

MainActivity.java


@SuppressWarnings("all")
public class MainActivity extends AppCompatActivity implements
GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {

private final int LOCATION_PERMISSION_REQUEST_CODE = 200;
private String[] PERMISSIONS;
private SupportMapFragment mapFragment;
private GoogleMap googleMap;
private Location currentLocation;
private FusedLocationProviderClient mFusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
checkPermissions();
}
private void initData() {
PERMISSIONS = new String[]{
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
};
googleMap = null;
currentLocation = null;
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
private void checkPermissions() {
if (hasPermissions(this)) {
mapFragment.getMapAsync(this);
} else {
askLocationPermission();
}
}
private void getLastLocation() {
Task<Location> locationTask = mFusedLocationClient.getLastLocation();
locationTask.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
currentLocation = location;
zoomOnCurrentPlace();
}
});
}

private void askLocationPermission() {
if (ActivityCompat.checkSelfPermission(this, PERMISSIONS[1]) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE);
} else {
mapFragment.getMapAsync(this);
}
}

private boolean hasPermissions(Context context) {
if (context != null && PERMISSIONS != null) {
for (String permission : PERMISSIONS) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}

@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
Toast.makeText(this, "Start OnMapReady", Toast.LENGTH_LONG).show();
this.googleMap = googleMap;
this.googleMap.setMapType(this.googleMap.MAP_TYPE_NORMAL);
this.googleMap.setMyLocationEnabled(true);
this.googleMap.setOnMyLocationButtonClickListener(this);
this.googleMap.setOnMyLocationClickListener(this);
this.googleMap.getUiSettings().setZoomControlsEnabled(true);

this.googleMap.setOnMapClickListener(latLng -> {
Toast.makeText(MainActivity.this, "Click on " + latLng, Toast.LENGTH_SHORT).show();
this.googleMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
});

getLastLocation();
}
private void zoomOnCurrentPlace() {
LatLng currentPlace = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
// Move the camera to the this.googleMap coordinates and zoom in closer.
googleMap.addMarker(new MarkerOptions().position(currentPlace).title("Ma position"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPlace, 17));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
boolean permissionsAreAccepted = true;
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE && grantResults.length > 0) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
permissionsAreAccepted = false;
break;
}
}
if (permissionsAreAccepted) {
mapFragment.getMapAsync(this);
}else {
askLocationPermission();
}
}
}

@Override
public void onMyLocationClick(@NonNull Location location) {
Toast.makeText(this, "Current location:n" + location, Toast.LENGTH_LONG)
.show();
}
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
.show();
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_options, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.normal_map:
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
case R.id.hybrid_map:
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
case R.id.satellite_map:
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.terrain_map:
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
}
return super.onOptionsItemSelected(item);
}
}

谢谢你的帮助:-)

我解决了我的问题,只要跟着做,一步一步来:

  1. 创建变量类型LocationCallback, LocationRequest和long
private LocationRequest mLocationRequest = null;
private LocationCallback mLocationCallback = null;
private final Long LOCATION_REQUEST_INTERVAL = 5000L;
  1. 在Oncreate中只初始化你的FusedLocationProviderClient, LocationCallback和map
private void initData() {
PERMISSIONS = new String[]{
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
};
googleMap = null;
currentLocation = null;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
currentLocation = locationResult.getLastLocation();
}
};
}
  1. 在OnCreate调用函数createLocationRequest
private void createLocationRequest() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(LOCATION_REQUEST_INTERVAL).setFastestInterval(LOCATION_REQUEST_INTERVAL);
//        requestLocationUpdate();
}
  1. 检查您的权限(Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION)

  2. 如果您有权限调用getLastLocation()与mFusedLocationClient

  3. 在getLastLocation中,当location != null,则googleMap.setLocationSource()

googleMap.setLocationSource(new LocationSource() {
@Override
public void activate(@NonNull OnLocationChangedListener onLocationChangedListener) {
onLocationChangedListener.onLocationChanged(currentLocation);
zoomOnCurrentPlace();
}
@Override
public void deactivate() {
Toast.makeText(MainActivity.this, "LocationSource deactivated", Toast.LENGTH_SHORT).show();
}
}); 

如果你没有权限

  1. 如果你没有权限,问他们
private void askLocationPermission() {
ActivityCompat.requestPermissions(this, PERMISSIONS, LOCATION_PERMISSION_REQUEST_CODE);
}
  1. 然后在onRequestPermissionsResult中,如果权限被授予,则
googleMap.setMyLocationEnabled(true);
requestLocationUpdate();
getLastLocation();
  1. Elseif只是回调askLocationPermission函数,不要忘记创建requestLocationUpdate函数
private void requestLocationUpdate() {
mFusedLocationClient.requestLocationUpdates(
mLocationRequest,
mLocationCallback,
Looper.myLooper()
);

我希望它能帮助到别人。

相关内容

  • 没有找到相关文章

最新更新