I have been trying to get the latitude and longitude of locations I have searched for in the Mapbox Search Bar API, and am using the following code implementation and it works perfectly for everything except for extracting coordinates. All of the data is fine except the coordinates and even the specific elements such as latitude or longitude. this is the code below:
var values: [MapCells] = []
let placeAutocomplete = PlaceAutocomplete()
// Define processSuggestions as a class method
func processSuggestions(suggestions: [PlaceAutocomplete.Suggestion]) {
for value in suggestions {
values.append(
MapCells(Name: value.name,
Address: (value.description) ?? "No address avaliable...",
DistanceInKM: "\(((value.distance ?? 0.0) * 0.001).rounded())km",
Latitude: value.coordinate?.latitude, **--- Returns nil???**
Longitude: value.coordinate?.longitude)) **--- Returns nil???**
}
}
func searchForPlace(value: String) {
// Then in your search function
placeAutocomplete.suggestions(for: value) { [self] result in
switch result {
case .success(let suggestions):
values = []
self.processSuggestions(suggestions: suggestions)
SearchTable.reloadData()
case .failure(let error):
print(error)
}
}
}
I have used their A.I. service to try to make a specific "for value in value.coordinates {..." but it didn't work. I also tried to extract it using external values such as a separate CLLocation variable but it didn't work either.
You're trying to access coordinate
but it does not exist in the data returned by PlaceAutoComplete.suggestions()
. This happens because the Search SDK for iOS is using the Search Box API behind the scenes, which is a two-step search process. The first step gets suggestions, the second "retrieves" full details about a suggestion after the user selects one. The first call to get suggestions does not include coordinates. You can learn more about the data actually returned by these API calls using the Search Box API playground: https://docs.mapbox.com/playground/search-box/suggest-retrieve/.
You need to call PlaceAutoComplete.select(suggestion: selectedSuggestion)
as outlined in step 4 on this guide: https://docs.mapbox.com/ios/search/guides/search-by-text/
That response will include the coordinates
data you're looking for.