nearbySearch method

Future<List<LocationResult>> nearbySearch({
  1. required double latitude,
  2. required double longitude,
  3. double radius = 5000,
  4. String? type,
  5. String? keyword,
})

Search for nearby places

Implementation

Future<List<LocationResult>> nearbySearch({
  required double latitude,
  required double longitude,
  double radius = 5000, // meters
  String? type,
  String? keyword,
}) async {
  if (!isInitialized) {
    throw Exception('Google Places API key not initialized. Call initialize() first.');
  }

  try {
    final uri = Uri.parse('$_baseUrl/nearbysearch/json').replace(queryParameters: {
      'location': '$latitude,$longitude',
      'radius': radius.toString(),
      'key': _apiKey!,
      if (type != null) 'type': type,
      if (keyword != null) 'keyword': keyword,
    });

    final response = await http.get(uri);

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

      if (data['status'] == 'OK') {
        final results = data['results'] as List<dynamic>;
        return results.map((result) {
          final geometry = result['geometry'];
          final location = geometry['location'];

          return LocationResult.fromGooglePlace(
            result,
            location['lat'].toDouble(),
            location['lng'].toDouble(),
          );
        }).toList();
      } 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 search nearby places: $e');
  }
}