getNearbyPlacesMap method
Retrieves nearby places from the Google Places API and returns a CustomMapPage.
Parameters:
position
: User's current GPS position.radius
: Search radius in meters (default: 1500).type
: Optional place type (e.g.'restaurant'
,'museum'
).title
: Title to show at the top of the map.onBack
: Callback for the back button on the map page.fallbackPosition
: Used if no places are found; defaults to user's location.
Returns:
- A CustomMapPage containing markers for each nearby place.
Throws:
- PlacesApiException if the HTTP request fails or the Places API response status is not OK.
Implementation
Future<CustomMapPage> getNearbyPlacesMap({
required Position position,
int radius = 50000,
String? type,
required String title,
required VoidCallback? onBack,
LatLng? fallbackPosition,
}) async {
final apiKey = dotenv.env['API_KEY'];
final lat = position.latitude;
final lng = position.longitude;
var url = Uri.parse(
'https://maps.googleapis.com/maps/api/place/nearbysearch/json?'
'location=$lat,$lng'
'&radius=$radius'
'&type=$type'
'&keyword=$title'
'&key=$apiKey',
);
if (type != null) {
url = Uri.parse('$url&type=$type');
}
final response = await http.get(url);
if (response.statusCode != 200) {
throw PlacesApiException('HTTP error: ${response.statusCode}');
}
final data = json.decode(response.body);
if (data['status'] != 'OK') {
throw PlacesApiException('Places API error: ${data['status']}');
}
final markers = <Marker>[];
int markerId = 0;
for (var place in data['results']) {
final placeLat = place['geometry']['location']['lat'];
final placeLng = place['geometry']['location']['lng'];
final placeId = place['place_id'];
final name = place['name'];
markers.add(
Marker(
markerId: MarkerId('place_${markerId++}_$placeId'),
position: LatLng(placeLat, placeLng),
infoWindow: InfoWindow(title: name),
icon: BitmapDescriptor.defaultMarkerWithHue(
BitmapDescriptor.hueOrange,
),
),
);
}
return CustomMapPage(
title: title,
markers: markers,
onBack: onBack,
fallbackPosition: fallbackPosition ?? LatLng(lat, lng),
);
}