add cache for latitude and use in searchdelagate

This commit is contained in:
Valentin CZERYBA 2024-11-23 13:29:25 +01:00
parent 23aec689f1
commit 627eb778ad
2 changed files with 23 additions and 40 deletions

View File

@ -367,7 +367,11 @@ class _MyHomePageState extends State<ListItemMenu> {
border: OutlineInputBorder(), border: OutlineInputBorder(),
suffixIcon: IconButton( suffixIcon: IconButton(
icon: const Icon(Icons.clear), icon: const Icon(Icons.clear),
onPressed: () { onPressed: () async {
SharedPreferences prefs =
await SharedPreferences.getInstance();
prefs.remove("city_lat");
prefs.remove("city_long");
setState(() { setState(() {
Datepicker.text = ''; Datepicker.text = '';
}); });
@ -464,7 +468,7 @@ class _MyHomePageState extends State<ListItemMenu> {
onPressed: () { onPressed: () {
showSearch( showSearch(
context: context, context: context,
delegate: SearchDelegateExample(geoQuery: inputGeo.text), delegate: SearchDelegateExample(),
); );
}, },
), ),

View File

@ -11,11 +11,7 @@ import 'dart:math';
import '../variable/globals.dart' as globals; import '../variable/globals.dart' as globals;
class SearchDelegateExample extends SearchDelegate { class SearchDelegateExample extends SearchDelegate {
final String geoQuery; SearchDelegateExample();
SearchDelegateExample({
required this.geoQuery,
});
@override @override
List<Widget> buildActions(BuildContext context) { List<Widget> buildActions(BuildContext context) {
@ -43,7 +39,7 @@ class SearchDelegateExample extends SearchDelegate {
Widget buildResults(BuildContext context) { Widget buildResults(BuildContext context) {
// Perform the search and return the results // Perform the search and return the results
return FutureBuilder<List<Events>>( return FutureBuilder<List<Events>>(
future: searchPosts(query, geoQuery), future: searchPosts(query),
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) { if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator()); return const Center(child: CircularProgressIndicator());
@ -79,45 +75,28 @@ class SearchDelegateExample extends SearchDelegate {
return Container(); // Implement suggestions if needed return Container(); // Implement suggestions if needed
} }
Future<List<Events>> searchPosts(String query, String geoQuery) async { Future<List<Events>> searchPosts(String query) async {
SharedPreferences prefs = await SharedPreferences.getInstance(); SharedPreferences prefs = await SharedPreferences.getInstance();
var accessToken = prefs.getString("access_token") ?? ""; var accessToken = prefs.getString("access_token") ?? "";
var latitude = prefs.getDouble("city_lat") ?? 0.0;
var longitude = prefs.getDouble("city_long") ?? 0.0;
final List<Events> body = []; final List<Events> body = [];
if (accessToken.isNotEmpty) { if (accessToken.isNotEmpty) {
DateTime currentDate = DateTime.now(); DateTime currentDate = DateTime.now();
var url = Uri.parse( var url = Uri.parse(
"${globals.api}/events/search?item=${query}&current_dateime=${currentDate.toString()}"); "${globals.api}/events/search?item=${query}&current_dateime=${currentDate.toString()}");
if (geoQuery.isNotEmpty) { if ((latitude != 0.0) && (longitude != 0.0)) {
await dotenv.load( // Now use the latitude and longitude to get events within a 50km radius
fileName: ".env"); // Load your .env for the Mapbox access token double radiusInKm = 50;
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; double latDistance = radiusInKm / 111.0;
final geocodeUrl = Uri.parse( double lonDistance = radiusInKm / (111.0 * cos(latitude * pi / 180));
'https://api.mapbox.com/geocoding/v5/mapbox.places/$geoQuery.json?access_token=$mapboxAccessToken'); double minLat = latitude - latDistance;
final geocodeResponse = await http.get(geocodeUrl); double maxLat = latitude + latDistance;
if (geocodeResponse.statusCode == 200) { double minLon = longitude - lonDistance;
final geocodeData = json.decode(geocodeResponse.body); double maxLon = longitude + lonDistance;
if (geocodeData['features'].isNotEmpty) { // Construct the search URL with the item query and latitude/longitude bounds
final coordinates = url = Uri.parse(
geocodeData['features'][0]['geometry']['coordinates']; "${globals.api}/events/search?item=${query}&min_lat=${minLat}&max_lat=${maxLat}&min_lon=${minLon}&max_lon=${maxLon}&current_dateime=${currentDate.toString()}");
final longitude = coordinates[0]; // Longitude
final latitude = coordinates[1]; // Latitude
// Now use the latitude and longitude to get events within a 50km radius
double radiusInKm = 50;
double latDistance = radiusInKm / 111.0;
double lonDistance =
radiusInKm / (111.0 * cos(latitude * pi / 180));
double minLat = latitude - latDistance;
double maxLat = latitude + latDistance;
double minLon = longitude - lonDistance;
double maxLon = longitude + lonDistance;
// Construct the search URL with the item query and latitude/longitude bounds
url = Uri.parse(
"${globals.api}/events/search?item=${query}&min_lat=${minLat}&max_lat=${maxLat}&min_lon=${minLon}&max_lon=${maxLon}&current_dateime=${currentDate.toString()}");
}
}
} }
final response = await http.get(url, headers: { final response = await http.get(url, headers: {
"Content-Type": "application/json", "Content-Type": "application/json",