如何通过经纬度坐标获取GMSPlace对象?
Great question—let’s break this down clearly for you, since the official docs can be a bit vague on these specifics.
Can you create a custom GMSPlace object?
Short answer: No, you can’t directly instantiate a custom GMSPlace object yourself.
GMSPlace is designed as an immutable class in the Google Places iOS SDK, meaning all its initialization methods are internal (not exposed to developers). The SDK restricts creation of GMSPlace instances to only those returned by its own APIs (like fetching place details or current location places) to ensure data consistency and validity.
If you need to store or work with place-like data that you control (e.g., mock data for testing, or custom place entries), your best bet is to create your own model class. For example:
struct CustomPlace { let coordinate: CLLocationCoordinate2D let name: String? let formattedAddress: String? // Add any other properties you need from GMSPlace }
You can then populate this struct with your own data or copy values from a fetched GMSPlace as needed.
Can you get a GMSPlace using specific coordinates?
Yes, but it requires a two-step process since you can’t directly fetch a GMSPlace from coordinates alone. Here’s how to do it:
- Reverse geocode the coordinates to get a Place ID
Use theGMSGeocoderto convert your target latitude/longitude into aGMSAddress, which includes a Place ID if one exists for that location. - Fetch the full
GMSPlaceusing the Place ID
Pass the retrieved Place ID toGMSPlacesClient’sfetchPlace(fromPlaceID:placeFields:)method to get the completeGMSPlaceobject.
Here’s a code example in Swift:
import GoogleMaps import GooglePlaces // Define your target coordinates let targetCoordinate = CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194) // Step 1: Reverse geocode to get Place ID let geocoder = GMSGeocoder() geocoder.reverseGeocodeCoordinate(targetCoordinate) { response, error in guard let address = response?.firstResult(), let placeID = address.placeID else { print("Failed to reverse geocode: \(error?.localizedDescription ?? "Unknown error")") return } // Step 2: Fetch GMSPlace using Place ID let placesClient = GMSPlacesClient.shared() // Specify the fields you need (adjust based on your requirements) let placeFields: GMSPlaceField = [.name, .formattedAddress, .coordinate, .rating] placesClient.fetchPlace(fromPlaceID: placeID, placeFields: placeFields) { place, error in guard let place = place else { print("Failed to fetch place details: \(error?.localizedDescription ?? "Unknown error")") return } // Use the GMSPlace object here print("Fetched Place: \(place.name ?? "Unnamed Place")") print("Address: \(place.formattedAddress ?? "No address")") print("Coordinate: \(place.coordinate.latitude), \(place.coordinate.longitude)") } }
Note that this relies on the Google Geocoding API (included with the Places SDK) and requires your API key to be properly configured with the necessary permissions.
内容的提问来源于stack exchange,提问作者J Doe

