Java Can';t在谷歌地图活动中导航,它总是返回到我当前的位置
我是android开发新手,正在开发一款需要谷歌地图活动的应用程序。 我面临的问题是,当我试图在地图上平移(或滚动)时,我会立即恢复到最初设置的当前位置。 一点帮助将是非常好的,因为我被困在这一点上,无法找到解决办法。 代码如下:-Java Can';t在谷歌地图活动中导航,它总是返回到我当前的位置,java,android,google-maps-android-api-3,Java,Android,Google Maps Android Api 3,我是android开发新手,正在开发一款需要谷歌地图活动的应用程序。 我面临的问题是,当我试图在地图上平移(或滚动)时,我会立即恢复到最初设置的当前位置。 一点帮助将是非常好的,因为我被困在这一点上,无法找到解决办法。 代码如下:- protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMapsBinding.infla
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 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;
mMap.getUiSettings().setScrollGesturesEnabled(true);
locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener=new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
centerOnMap(location,"Your Location");
}
};
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,0,0,locationListener);
Location lastKnownLocation=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centerOnMap(lastKnownLocation,"Your Location");
}
}
public void centerOnMap(Location location,String address)
{
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title(address));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull @org.jetbrains.annotations.NotNull String[] permissions, @NonNull @org.jetbrains.annotations.NotNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
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);
}
}
}
}您可能有但未说明的一项要求是: 当
lastLocation
可用且用户已
未移动地图,然后将地图居中放置在该位置。如果
用户已移动地图,请不要将地图居中In
无论哪种情况,在用户位置添加一个标记
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setScrollGesturesEnabled(true);
getLastLocation();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(@NonNull LatLng latLng) {
Location location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
centerOnMap(location,"Your location");
}
});
}
@SuppressLint("MissingPermission")
private void getLastLocation() {
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
centerOnMap(location,"Your Location");
}
}
});
} else {
Toast.makeText(this, "Please turn on" + " your location...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
@SuppressLint("MissingPermission")
private void requestNewLocationData() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
centerOnMap(mLastLocation,"Your Location");
}
};
private boolean checkPermissions() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void centerOnMap(Location location,String address)
{
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(address));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
getLastLocation();
}
}
在走得太远之前,必须注意谷歌地图提供了
功能类似于您试图实现的功能,但您仍然需要“移动相机”。标记是一个蓝色的球,而不是典型的标记。请参阅myMap.setMyLocationEnabled(true)
。就这样!在获得地图权限后执行此操作
但是如果你不想使用它,那么这里是你需要的简单更改
请记住,LocationManager
getLastKnownLocation
可以返回
如果设备没有(尚未)设置,则为null。所以我推荐一个小的
更改一点无关的内容-只需让位置侦听器完成所有工作,并摆脱以下一种特殊情况:
// this is where you initially check permissions and have them.
else{
locationManager.requestLocationUpdates (LocationManager.GPS_PROVIDER,0,0,locationListener);
// Here I removed the last location centering and let the
// location listener always handle it.
}
这就打开了可能性
用户可以与地图交互,最终到达最后一个位置。我理解这是你试图解决的问题
(顺便说一句,在我看来,你把android.location.LocationManager
和
FusedLocationProviderApi(com.google.android.gms.location)的FusedLocationProviderApi,因此我无法获取您的
由于不兼容的LocationListener
s,要编译的代码。
不幸的是,GoogleMaps有两个LocationListener
类
为了确保进一步了解,您必须包含您的导入。)
无论如何
当地图第一次准备就绪(onMapReady
)时,地图的摄像头将被关闭
以(0,0)
为中心。您可以获取摄像机的目标位置(中心)
随时使用LatLng tgtCtr=mMap.getCameraPosition().target代码>
奇怪的是,要知道用户是否
以任何方式与地图交互:滚动事件生成相机
触摸事件时的更改会生成单独的事件。相机更换
无法独占使用,因为您的代码或用户只能
不移动地图的缩放。你可以走这条路,但是
为了回答这个问题,为了简单起见,摄像机
使用目标
声明类实例变量(与定义mMap
的区域相同):
因此,在分配mMap
后的onMapReady
中,执行以下操作:
tgtCtr = mMap.getCameraPosition().target;
因此,假设您的代码在发布时存在(非常接近),然后
改变可能有助于:
// This change simply restricts centering of the map on location
// update to only when user has not moved the map (scrolled).
@Override
public void onLocationChanged(@NonNull Location location) {
LatLng currentCtr = mMap.getCamaraPosition().target;
// This is not the ideal check since `double` comparisons
// should account for epsilon but in this case of (0,0) it should work.
// Alternatively you could compute the distance of current
// center to (0,0) and then use an epsilon:
// see `com.google.maps.android.SphericalUtil.computeDistanceBetween`.
if (currentCtr.latitude == 0 && currentCtr.longitude == 0) {
centerOnMap(location,"Your Location");
}
}
保存为用户添加的标记似乎也是一个好主意
位置-这是可选的,但可以方便地防止多个标记
从添加到该位置:
// Define a class instance variable
Marker myLocMarker = nulll;
// and then in centerOnMap
public void centerOnMap(Location location, String address)
{
// ... other code
if (myLocMarker == null) {
myLocMarker = mMap.addMarker(new MarkerOptions().position(userLocation).title(address));
}
// ... more code
}
所以,真正的唯一困难是弄清楚“有
用户移动了地图。“在这种情况下,根据最初的要求
您可能不想移动地图。正如您在评论部分提到的,请使用FusedLocationProviderClient而不是LocationManager。
在应用程序级渐变中添加实现'com.google.android.gms:play services location:17.0.0'
。别忘了为精细位置添加清单权限
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setScrollGesturesEnabled(true);
getLastLocation();
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
@Override
public void onMapLongClick(@NonNull LatLng latLng) {
Location location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(latLng.latitude);
location.setLongitude(latLng.longitude);
centerOnMap(location,"Your location");
}
});
}
@SuppressLint("MissingPermission")
private void getLastLocation() {
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
centerOnMap(location,"Your Location");
}
}
});
} else {
Toast.makeText(this, "Please turn on" + " your location...", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
}
@SuppressLint("MissingPermission")
private void requestNewLocationData() {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
centerOnMap(mLastLocation,"Your Location");
}
};
private boolean checkPermissions() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void centerOnMap(Location location,String address)
{
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(userLocation).title(address));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
getLastLocation();
}
}
公共类MapsActivity扩展了FragmentActivity在MapreadyCallback上的实现{
私有谷歌地图;
FusedLocationProviderClient mFusedLocationClient;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
mFusedLocationClient=LocationServices.getFusedLocationProviderClient(此);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
mMap.getUiSettings().setScrollGesturesEnabled(true);
getLastLocation();
mMap.setOnMapLongClickListener(新的GoogleMap.OnMapLongClickListener(){
@凌驾
单击时的公共无效(@NonNull LatLng LatLng){
位置=新位置(LocationManager.GPS\U提供程序);
位置。设置纬度(纬度);
位置设置经度(纬度经度);
centerOnMap(位置,“您的位置”);
}
});
}
@SuppressLint(“丢失许可”)
私有void getLastLocation(){
if(checkPermissions()){
如果(isLocationEnabled()){
mFusedLocationClient.getLastLocation().addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
位置=task.getResult();
if(位置==null){
requestNewLocationData();
}否则{
centerOnMap(位置,“您的位置”);
}
}
});
}否则{
Toast.makeText(这是“请打开”+“您的位置…”),Toast.LENGTH\u LONG.show();
意向意向=新意向(设置、动作、位置、来源、设置);
星触觉(意向);
}
}否则{
请求权限();
}
}
@SuppressLint(“丢失许可”)
私有void requestNewLocationData(){
LocationRequest MLLocationRequest=新的LocationRequest();
mLocationRequest.setPriority(位置请求.优先级高精度);
位置