autoCompleteSearch method
Fetches the place autocomplete list with the query place.
Implementation
Future<void> autoCompleteSearch(String place) async {
place = place.replaceAll(" ", "+");
final countries = widget.countries;
// Currently, you can use components to filter by up to 5 countries. from https://developers.google.com/places/web-service/autocomplete
String regionParam = countries.isNotEmpty == true
? "&components=country:${countries.sublist(0, min(countries.length, 5)).join('|country:')}"
: "";
var endpoint =
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$place$regionParam&key=${widget.apiKey}&sessiontoken=$sessionToken";
if (locationResult != null) {
endpoint += "&location=${locationResult?.latLng.latitude},"
"${locationResult?.latLng.longitude}";
}
try {
final response = await http.get(
Uri.parse(endpoint),
);
logger.i(endpoint);
logger.v(response.body);
if (response.statusCode == 200) {
Map<String, dynamic> data = jsonDecode(response.body);
List<dynamic> predictions = data['predictions'];
List<RichSuggestion> suggestions = [];
if (predictions.isEmpty) {
AutoCompleteItem aci = AutoCompleteItem();
aci.text = S.of(context).no_result_found;
aci.offset = 0;
aci.length = 0;
suggestions.add(RichSuggestion(aci, () {}));
} else {
for (dynamic t in predictions) {
AutoCompleteItem aci = AutoCompleteItem();
aci.id = t['place_id'];
aci.text = t['description'];
aci.offset = t['matched_substrings'][0]['offset'];
aci.length = t['matched_substrings'][0]['length'];
suggestions.add(
RichSuggestion(
aci,
() {
decodeAndSelectPlace(aci.id);
},
),
);
}
}
displayAutoCompleteSuggestions(suggestions);
}
} catch (error) {
logger.e(error);
logger.i(endpoint);
}
}