Google Places API弃用后,如何集成地图碎片实现地点选择?
Hey there! I totally get your frustration—those old map fragments with the drag-and-drop pin were super convenient for use cases like delivery addresses or ride-hailing pickups. Let me clear this up for you:
The Short Answer
You didn’t miss a step! Google has phased out the built-in map fragment that came bundled with the older Places API versions as part of their API updates. This is intentional, and the new architecture requires a slightly different approach to recreate that familiar pin-dropping experience.
How to Recreate the Pin-Dropping Experience Now
Here are the two most straightforward ways to get that functionality back:
1. Combine Place Autocomplete + SupportMapFragment
This is the official recommended approach:
- First, add the
AutocompleteSupportFragmentto let users search for locations (or start with a blank map if you prefer). - Then, integrate a
SupportMapFragmentin your layout, initialize the GoogleMap instance, and add a draggable marker. - Listen for marker drag events to capture the final selected position, then use the Places API’s
fetchPlace()method to get detailed location data.
Quick code snippet to set up the draggable marker:
// Get the SupportMapFragment and request notification when the map is ready val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync { googleMap -> // Add a draggable marker at a default location (e.g., user's current location) val initialLatLng = LatLng(37.7749, -122.4194) // Example: San Francisco val marker = googleMap.addMarker( MarkerOptions() .position(initialLatLng) .draggable(true) .title("Drag to select location") ) // Listen for when the marker is dropped googleMap.setOnMarkerDragListener(object : GoogleMap.OnMarkerDragListener { override fun onMarkerDragStart(p0: Marker) {} override fun onMarkerDrag(p0: Marker) {} override fun onMarkerDragEnd(marker: Marker) { val selectedLatLng = marker.position // Now fetch place details using selectedLatLng with Places API fetchPlaceDetails(selectedLatLng) } }) }
2. Build a Custom Pin-Dropping Component
If you want full control over the UI (matching the exact old experience), you can:
- Create a custom view that overlays a draggable pin on top of a
MapVieworSupportMapFragment. - Use touch listeners to track when the user drags the pin, update the map camera to follow the pin, and capture the final coordinates once the user releases it.
- Again, use the Places API to fetch location details for the selected coordinates.
What About Compatibility Libraries?
While some third-party compatibility libraries might exist, Google strongly recommends migrating to the new official components since the old map fragments are no longer maintained. Using unsupported libraries could lead to bugs, security issues, or breakage in future Android/Google Play Services updates.
内容的提问来源于stack exchange,提问作者Shyamnath Mallinathan

