Android Studio Google Map拖拽Marker:需移除初始Marker
解决方案
要实现移除初始Marker的功能,你需要先保存初始Marker的引用,然后在用户长按地图生成新的可拖拽Marker时,移除这些初始Marker。具体实现步骤如下:
1. 添加成员变量保存Marker引用
在MapsActivity类中新增以下成员变量,用于跟踪初始Marker和当前可拖拽Marker:
private Marker initialUaeMarker; // 保存通过"uae"搜索添加的初始Marker private Marker userLocationMarker; // 保存用户位置的Marker private Marker currentDraggableMarker; // 保存当前的可拖拽Marker
2. 保存初始Marker的引用
修改onMapReady方法中添加Marker的代码,将返回的Marker对象赋值给对应变量:
try { List<Address> addresses = geocoder.getFromLocationName("uae", 1); if (addresses.size() > 0) { Address address = addresses.get(0); LatLng london = new LatLng(address.getLatitude(), address.getLongitude()); MarkerOptions markerOptions = new MarkerOptions() .position(london) .title(address.getLocality()); // 保存初始Marker引用 initialUaeMarker = mMap.addMarker(markerOptions); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(london, 16)); } } catch (IOException e) { e.printStackTrace(); }
修改zoomToUserLocation方法中添加Marker的代码:
locationTask.addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20)); // 保存用户位置Marker引用 userLocationMarker = mMap.addMarker(new MarkerOptions().position(latLng)); } });
3. 长按地图时移除初始Marker并管理可拖拽Marker
修改onMapLongClick方法,在添加新的可拖拽Marker前,先移除所有初始Marker和之前的可拖拽Marker:
@Override public void onMapLongClick(LatLng latLng) { Log.d(TAG, "onMapLongClick: " + latLng.toString()); // 移除初始Marker if (initialUaeMarker != null) { initialUaeMarker.remove(); initialUaeMarker = null; } if (userLocationMarker != null) { userLocationMarker.remove(); userLocationMarker = null; } // 移除之前的可拖拽Marker(避免多个拖拽Marker存在) if (currentDraggableMarker != null) { currentDraggableMarker.remove(); } try { List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); if (addresses.size() > 0) { Address address = addresses.get(0); String streetAddress = address.getAddressLine(0); // 添加新的可拖拽Marker并保存引用 currentDraggableMarker = mMap.addMarker(new MarkerOptions() .position(latLng) .title(streetAddress) .draggable(true) ); } } catch (IOException e) { e.printStackTrace(); } }
修改后的完整代码
package com.restaurant.grillizadmin; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationServices; 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.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.restaurant.grillizadmin.Domain.Items; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener { private static final String TAG = "MapsActivity"; private GoogleMap mMap; private Geocoder geocoder; private int ACCESS_LOCATION_REQUEST_CODE = 10001; FusedLocationProviderClient fusedLocationProviderClient; private Marker initialUaeMarker; // 保存通过"uae"搜索添加的初始Marker private Marker userLocationMarker; // 保存用户位置的Marker private Marker currentDraggableMarker; // 保存当前的可拖拽Marker @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // 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); geocoder = new Geocoder(this); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); mMap.setOnMapLongClickListener(this); mMap.setOnMarkerDragListener(this); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { enableUserLocation(); zoomToUserLocation(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_LOCATION_REQUEST_CODE); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_LOCATION_REQUEST_CODE); } } try { List<Address> addresses = geocoder.getFromLocationName("uae", 1); if (addresses.size() > 0) { Address address = addresses.get(0); LatLng london = new LatLng(address.getLatitude(), address.getLongitude()); MarkerOptions markerOptions = new MarkerOptions() .position(london) .title(address.getLocality()); initialUaeMarker = mMap.addMarker(markerOptions); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(london, 16)); } } catch (IOException e) { e.printStackTrace(); } } private void enableUserLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mMap.setMyLocationEnabled(true); } private void zoomToUserLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } Task<Location> locationTask = fusedLocationProviderClient.getLastLocation(); locationTask.addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 20)); userLocationMarker = mMap.addMarker(new MarkerOptions().position(latLng)); } }); } @Override public void onMapLongClick(LatLng latLng) { Log.d(TAG, "onMapLongClick: " + latLng.toString()); // 移除初始Marker if (initialUaeMarker != null) { initialUaeMarker.remove(); initialUaeMarker = null; } if (userLocationMarker != null) { userLocationMarker.remove(); userLocationMarker = null; } // 移除之前的可拖拽Marker if (currentDraggableMarker != null) { currentDraggableMarker.remove(); } try { List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); if (addresses.size() > 0) { Address address = addresses.get(0); String streetAddress = address.getAddressLine(0); currentDraggableMarker = mMap.addMarker(new MarkerOptions() .position(latLng) .title(streetAddress) .draggable(true) ); } } catch (IOException e) { e.printStackTrace(); } } @Override public void onMarkerDragStart(Marker marker) { Log.d(TAG, "onMarkerDragStart: "); } @Override public void onMarkerDrag(Marker marker) { Log.d(TAG, "onMarkerDrag: "); } @Override public void onMarkerDragEnd(Marker marker) { Log.d(TAG, "onMarkerDragEnd: "); LatLng latLng = marker.getPosition(); try { List<Address> addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); if (addresses.size() > 0) { Address address = addresses.get(0); String streetAddress = address.getAddressLine(0); marker.setTitle(streetAddress); } } catch (IOException e) { e.printStackTrace(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == ACCESS_LOCATION_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { enableUserLocation(); zoomToUserLocation(); } else { // 可添加权限未授予的提示逻辑 } } } }
核心说明
- 通过保存Marker引用,调用
remove()方法即可从地图上移除对应Marker,移除后将引用置为null避免内存泄漏。 currentDraggableMarker变量确保每次长按只保留最新的可拖拽Marker,避免地图上出现多个拖拽Marker。
内容的提问来源于stack exchange,提问作者G PAC
相关产品推荐
相关产品推荐

