在我的应用程序中,我有一个按钮以编程方式获取位置。一切顺利,直到我意识到,一旦我添加位置标记,每次我请求位置时都会添加新标记。因此,我添加了一个if语句,在我看来是合乎逻辑的但是不能按照我的意愿运行。当我第一次获得位置时,一切都很好,并放置一个标记。当我再次按下位置按钮时,标记将被删除,并且不会添加新标记。该应用程序在我的手机上编译没有问题。我究竟做错了什么?
public void showCurrentLocation(MenuItem item) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// 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 ActivityCompat#requestPermissions for more details.
return;
}
Location currentLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (currentLocation == null){
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_gps_view, null);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
LatLng latLng = new LatLng(
currentLocation.getLatitude(),
currentLocation.getLongitude()
);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);
mMap.animateCamera(update);
if (myPosition != null){
myPosition.remove();
} else {
myPosition = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_icon))
.position(latLng)
.title("I'm here!"));
}
}
}
答案 0 :(得分:1)
当Marker
已经存在但您没有再次添加时,您正从地图中移除Marker
。
请注意,当您从地图中删除标记时,它不是null
,它的状态是未定义的。
当if
存在时,更改Marker
以更新Marker
的位置:
if (myPosition != null){
myPosition.setPosition(latLng);
} else {
myPosition = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_location_icon))
.position(latLng)
.title("I'm here!"));
}