gpt4 book ai didi

android - 打开我的应用程序时如何将相机移动到当前位置?

转载 作者:行者123 更新时间:2023-11-29 02:25:30 24 4
gpt4 key购买 nike

我需要你的帮助。

如何在打开应用程序时立即将相机移动到当前位置?

我有一个可用的按钮(如果我单击它,它会将相机移动到我当前的位置),但是当我打开该应用程序时,相机设置在海洋中央。我想打开应用程序,相机已经设置在我当前的位置。

这是我的代码:

MapsActivity.java

    import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.api.GoogleApi;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
checkUserLocationPermission();
}

// 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);
}

/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
/*disabling toolbar (it is used to continue using this app without having to
use the official google maps app)*/

mMap.getUiSettings().setMapToolbarEnabled(false);
}

public boolean checkUserLocationPermission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code );
}
else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code );
}
return false;
}
else{
return true;
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case Request_User_Location_Code:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(googleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else{
Toast.makeText(this, "Permesso vietato", Toast.LENGTH_SHORT).show();
}
return;
}
}

protected synchronized void buildGoogleApiClient(){

googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();

googleApiClient.connect();


}

@Override
public void onLocationChanged(Location location) {
lastLocation = location;

if(currentUserLocationMarker != null){
currentUserLocationMarker.remove();
}

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

MarkerOptions markerOptions = new MarkerOptions();

markerOptions.position(latLng);
markerOptions.title("Posizione corrente");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

currentUserLocationMarker = mMap.addMarker(markerOptions);

mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(11));

if (googleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}

@Override
public void onConnected(@Nullable Bundle bundle) {

locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
}

activity_maps.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
class="com.google.android.gms.maps.SupportMapFragment"/>

已经在我的 AndroidManifest.xml 中添加了:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

感谢您的帮助。

最佳答案

所以你已经完成了几乎所有的工作。您只需要更进一步。

首先要了解,setMyLocationEnabled 设置为 true 时会在 map 上添加该位置罗盘按钮。这是您单击以查找当前位置的内容。好的开始。

您还需要在初始化 map 时将相机设置为您当前的位置。

if(locationPermissionGranted){
Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if(task.isSuccessful()){
// Set the maps camera to current location
lastKnownLocation = task.getResult();
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()), 12));
}
else{
Log.d(TAG, "Current location is null");
Log.e(TAG,"Exception: %s", task.getException());
map.moveCamera(CameraUpdateFactory.newLatLngZoom(defaultLocation, 12));
map.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}

试试这个。首先确保您已授予位置权限。然后尝试找到最后一个已知位置。 (如果您使用的是模拟器,请在尝试此代码之前尝试打开 Google map 。模拟器上的位置服务从未启动过)。它会尝试获取您当前的位置。如果成功,它将相机移动到该位置,如果失败,我已经设置了 map 移动到的默认位置,而不是在海洋中打开。

private LatLng defaultLocation = new LatLng(41.651031, -83.541939);

希望这对您有所帮助。

关于android - 打开我的应用程序时如何将相机移动到当前位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52481107/

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