SendTrain/lib/services/apis/google_places_service.dart

100 lines
2.6 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:uuid/uuid.dart';
class GooglePlacesService {
final sessionToken = Uuid().v4();
final apiKey = "AIzaSyBCjMCEAyyNVpsnVYvZj6VL1mmB98Vd6AE";
final client = Client();
void finish() {
client.close();
}
Future<List<Suggestion>?> fetchSuggestions(String input, String lang) async {
var headers = {
'Content-Type': 'application/json',
'X-Goog-Api-Key': apiKey,
"Access-Control-Allow-Origin": "*",
'X-Goog-FieldMask':
'places.displayName,places.id,places.formattedAddress,places.photos'
};
var request = Request('POST',
Uri.parse('https://places.googleapis.com/v1/places:searchText'));
request.body = json.encode({"textQuery": input});
request.headers.addAll(headers);
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
final result = json.decode(await response.stream.bytesToString());
if (result.isNotEmpty) {
return result['places']
.map<Suggestion>((p) => Suggestion(
placeId: p['id'],
description: p['displayName']['text'],
address: p['formattedAddress'],
imageReferences: p['photos']))
.toList();
} else {
return null;
}
} else {
throw Exception(response.reasonPhrase);
}
}
Future fetchPhoto(String name) async {
var headers = {
"Access-Control-Allow-Origin": "*",
};
var request = Request('GET',
Uri.parse('https://places.googleapis.com/v1/$name/media?key=$apiKey&maxWidthPx=800&skipHttpRedirect=true')
);
request.headers.addAll(headers);
StreamedResponse response = await request.send();
if (response.statusCode == 200) {
final result = json.decode(await response.stream.bytesToString());
if (result.isNotEmpty) {
return result;
} else {
return null;
}
} else {
throw Exception(response.reasonPhrase);
}
}
}
class Suggestion {
final String placeId;
final String description;
final String address;
final List<dynamic>? imageReferences;
Suggestion(
{required this.placeId,
required this.description,
required this.address,
this.imageReferences});
@override
String toString() {
return 'Suggestion(description: $description, placeId: $placeId)';
}
Map toJson() => {
'placeId': placeId,
'name': description,
'address': address,
'imageReferences': imageReferences
};
}