Android端Google Map Marker拖拽事件失效问题求助
Hey there! I notice you've set up the OnMarkerDragListener correctly, but your marker drag functionality isn't triggering—this is usually a simple fix, since markers are not draggable by default in the Google Maps Android API. Let's walk through the steps to get this working:
1. Enable Draggable Property for Your Markers
The key missing piece is explicitly turning on drag support for each marker you want to move. You can do this in two ways:
Option A: When Creating the Marker
Add .draggable(true) to your MarkerOptions while initializing the marker:
// Example of creating a draggable marker LatLng markerPosition = new LatLng(37.7749, -122.4194); // Replace with your target coordinates Marker marker = mGoogleMap.addMarker(new MarkerOptions() .position(markerPosition) .title("My Draggable Marker") .draggable(true)); // This line enables dragging functionality!
Option B: For Existing Markers
If you've already created markers and need to enable drag later, call setDraggable(true) directly on the Marker object:
// Enable drag for an existing marker instance yourExistingMarker.setDraggable(true);
2. Double-Check Your Listener Setup
Your existing OnMarkerDragListener implementation looks solid—you're attaching it to the initialized GoogleMap instance correctly in onMapReady, which is exactly what you need. Just to confirm, the listener will fire:
onMarkerDragStartwhen you start long-pressing and moving the markeronMarkerDragrepeatedly as you drag the marker across the maponMarkerDragEndwhen you release the marker
3. Full Updated Code Example
Here's how your onMapReady method should look with draggable markers integrated:
@Override public void onMapReady(final GoogleMap googleMap) { Log.d(TAG, "onMapReady()"); mGoogleMap = googleMap; mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); // Add a draggable marker (repeat this for all markers you want to drag) LatLng samplePosition = new LatLng(40.7128, -74.0060); mGoogleMap.addMarker(new MarkerOptions() .position(samplePosition) .draggable(true)); mGoogleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() { @Override public void onMarkerDragStart(Marker arg0) { Log.d("System out", "onMarkerDragStart..." + arg0.getPosition().latitude + "..." + arg0.getPosition().longitude); } @SuppressWarnings("unchecked") @Override public void onMarkerDragEnd(Marker arg0) { Log.d("System out", "onMarkerDragEnd..." + arg0.getPosition().latitude + "..." + arg0.getPosition().longitude); } @Override public void onMarkerDrag(Marker arg0) { Log.i("System out", "onMarkerDrag..."); } }); mGoogleMap.setOnMarkerClickListener(this); }
Testing the Fix
After making these changes, run your app, long-press the marker, and you should be able to drag it around the map. Check your Logcat—you'll see the corresponding log messages from your listener as you interact with the marker.
内容的提问来源于stack exchange,提问作者risbin.p

