Created
June 1, 2020 04:19
-
-
Save yshean/f2c54bf8637d85055065a58a14ed267f to your computer and use it in GitHub Desktop.
Place service v1 with autocomplete
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:convert'; | |
import 'dart:io'; | |
import 'package:http/http.dart'; | |
// For storing our result | |
class Suggestion { | |
final String placeId; | |
final String description; | |
Suggestion(this.placeId, this.description); | |
@override | |
String toString() { | |
return 'Suggestion(description: $description, placeId: $placeId)'; | |
} | |
} | |
class PlaceApiProvider { | |
final client = Client(); | |
PlaceApiProvider(this.sessionToken); | |
final sessionToken; | |
static final String androidKey = 'YOUR_API_KEY_HERE'; | |
static final String iosKey = 'YOUR_API_KEY_HERE'; | |
final apiKey = Platform.isAndroid ? androidKey : iosKey; | |
Future<List<Suggestion>> fetchSuggestions(String input, String lang) async { | |
final request = | |
'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$input&types=address&language=$lang&components=country:ch&key=$apiKey&sessiontoken=$sessionToken'; | |
final response = await client.get(request); | |
if (response.statusCode == 200) { | |
final result = json.decode(response.body); | |
if (result['status'] == 'OK') { | |
// compose suggestions in a list | |
return result['predictions'] | |
.map<Suggestion>((p) => Suggestion(p['place_id'], p['description'])) | |
.toList(); | |
} | |
if (result['status'] == 'ZERO_RESULTS') { | |
return []; | |
} | |
throw Exception(result['error_message']); | |
} else { | |
throw Exception('Failed to fetch suggestion'); | |
} | |
} | |
Future<Place> getPlaceDetailFromId(String placeId) async { | |
// if you want to get the details of the selected place by place_id | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment