getPlaceDetails method

Future<LocationResult?> getPlaceDetails({
  1. required String placeId,
  2. String? sessionToken,
  3. List<String> fields = const ['place_id', 'formatted_address', 'geometry/location', 'address_components'],
})

Get place details by place ID

Implementation

Future<LocationResult?> getPlaceDetails({
  required String placeId,
  String? sessionToken,
  List<String> fields = const [
    'place_id',
    'formatted_address',
    'geometry/location',
    'address_components'
  ],
}) async {
  if (!isInitialized) {
    throw Exception('Google Places API key not initialized. Call initialize() first.');
  }

  try {
    final uri = Uri.parse('$_baseUrl/details/json').replace(queryParameters: {
      'place_id': placeId,
      'fields': fields.join(','),
      'key': _apiKey!,
      if (sessionToken != null) 'sessiontoken': sessionToken,
    });

    final response = await http.get(uri);

    if (response.statusCode == 200) {
      final data = json.decode(response.body);

      if (data['status'] == 'OK') {
        final result = data['result'];
        final geometry = result['geometry'];
        final location = geometry['location'];

        return LocationResult.fromGooglePlace(
          result,
          location['lat'].toDouble(),
          location['lng'].toDouble(),
        );
      } else {
        throw Exception('Google Places API error: ${data['status']} - ${data['error_message'] ?? 'Unknown error'}');
      }
    } else {
      throw Exception('HTTP error: ${response.statusCode}');
    }
  } catch (e) {
    throw Exception('Failed to get place details: $e');
  }
}