Advertisement
tumuldousMadman

dart

May 16th, 2024
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 6.02 KB | Source Code | 0 0
  1. import 'dart:async';
  2. import 'dart:math';
  3. import 'package:flutter/material.dart';
  4. import 'package:google_maps_flutter/google_maps_flutter.dart';
  5. import 'package:location/location.dart';
  6. import 'package:flutter_local_notifications/flutter_local_notifications.dart';
  7.  
  8. class SimpleMap extends StatefulWidget {
  9.   const SimpleMap({super.key});
  10.  
  11.   @override
  12.   State<SimpleMap> createState() => _SimpleMapState();
  13. }
  14.  
  15. class _SimpleMapState extends State<SimpleMap> {
  16.   final LatLng destinationLocation = LatLng(-1.9501, 30.0589); // Example coordinates for KK 561 St
  17.   final Completer<GoogleMapController> _controller = Completer();
  18.  
  19.   Set<Marker> _markers = {}; // Initialize an empty set of markers
  20.   LatLng? currentLocation; // Assuming you have a way to get the current location
  21.   Location location = Location();
  22.   StreamSubscription<LocationData>? _locationSubscription;
  23.  
  24.   bool _notificationSentOutSide = false;
  25.   bool _notificationSentInSide = false;
  26.  
  27.   FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  28.  
  29.   @override
  30.   void initState() {
  31.     super.initState();
  32.     _initializeNotifications();
  33.     getCurrentLocation();
  34.   }
  35.  
  36.   void _initializeNotifications() {
  37.     const AndroidInitializationSettings initializationSettingsAndroid =
  38.         AndroidInitializationSettings('@mipmap/ic_launcher');
  39.  
  40.     final InitializationSettings initializationSettings = InitializationSettings(
  41.       android: initializationSettingsAndroid,
  42.     );
  43.  
  44.     flutterLocalNotificationsPlugin.initialize(initializationSettings);
  45.   }
  46.  
  47.   void getCurrentLocation() async {
  48.     currentLocation = await location.getLocation().then((value) {
  49.       currentLocation = LatLng(value.latitude!, value.longitude!);
  50.       addCurrentLocMarker(currentLocation!);
  51.       return currentLocation;
  52.     });
  53.  
  54.     _locationSubscription = location.onLocationChanged.listen((newLoc) {
  55.       setState(() {
  56.         currentLocation = LatLng(newLoc.latitude!, newLoc.longitude!);
  57.         addCurrentLocMarker(currentLocation!);
  58.         _checkGeofenceStatus(newLoc.latitude!, newLoc.longitude!);
  59.       });
  60.     });
  61.   }
  62.  
  63.   void addCurrentLocMarker(LatLng location) {
  64.     Marker currentLocMarker = Marker(
  65.       markerId: MarkerId('currentLocation'),
  66.       icon: BitmapDescriptor.defaultMarker,
  67.       position: location,
  68.       infoWindow: InfoWindow(title: 'Current Location', snippet: 'You are here'),
  69.     );
  70.     setState(() {
  71.       _markers.add(currentLocMarker);
  72.     });
  73.   }
  74.  
  75.   void addDestinationMarker() {
  76.     Marker destinationMarker = Marker(
  77.       markerId: MarkerId('destinationLocation'),
  78.       icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
  79.       position: destinationLocation,
  80.       infoWindow: InfoWindow(title: 'Destination Location', snippet: 'Destination location...'),
  81.     );
  82.     setState(() {
  83.       _markers.add(destinationMarker);
  84.     });
  85.   }
  86.  
  87.   void _checkGeofenceStatus(double latitude, double longitude) {
  88.     bool insideGeofence = _isLocationInsideGeofence(latitude, longitude);
  89.  
  90.     if (insideGeofence && !_notificationSentInSide) {
  91.       _triggerInSideNotification();
  92.       _notificationSentInSide = true;
  93.       _notificationSentOutSide = false;
  94.     } else if (!insideGeofence && !_notificationSentOutSide) {
  95.       _triggerOutSideNotification();
  96.       _notificationSentOutSide = true;
  97.       _notificationSentInSide = false;
  98.     }
  99.   }
  100.  
  101.   bool _isLocationInsideGeofence(double latitude, double longitude) {
  102.     // Define your geofence boundaries, for example, a 500m radius around the destination
  103.     double radiusInMeters = 500.0;
  104.     double distance = _calculateDistance(latitude, longitude, destinationLocation.latitude, destinationLocation.longitude);
  105.     return distance <= radiusInMeters;
  106.   }
  107.  
  108.   double _calculateDistance(double lat1, double lon1, double lat2, double lon2) {
  109.     const double p = 0.017453292519943295; // PI / 180
  110.     final double a = 0.5 -
  111.         cos((lat2 - lat1) * p) / 2 +
  112.         cos(lat1 * p) * cos(lat2 * p) *
  113.         (1 - cos((lon2 - lon1) * p)) / 2;
  114.     return 12742 * asin(sqrt(a)) * 1000; // 2 * R; R = 6371 km
  115.   }
  116.  
  117.   Future<void> _triggerInSideNotification() async {
  118.     const AndroidNotificationDetails androidPlatformChannelSpecifics =
  119.         AndroidNotificationDetails(
  120.       'geo_fence_channel',
  121.       'Geofence Notifications',
  122.       importance: Importance.max,
  123.       priority: Priority.high,
  124.     );
  125.     const NotificationDetails platformChannelSpecifics =
  126.         NotificationDetails(android: androidPlatformChannelSpecifics);
  127.     await flutterLocalNotificationsPlugin.show(
  128.       0,
  129.       'Inside Geofence',
  130.       'You are inside the geofence area.',
  131.       platformChannelSpecifics,
  132.     );
  133.     print('Inside geofence notification sent');
  134.   }
  135.  
  136.   Future<void> _triggerOutSideNotification() async {
  137.     const AndroidNotificationDetails androidPlatformChannelSpecifics =
  138.         AndroidNotificationDetails(
  139.       'geo_fence_channel',
  140.       'Geofence Notifications',
  141.       importance: Importance.max,
  142.       priority: Priority.high,
  143.     );
  144.     const NotificationDetails platformChannelSpecifics =
  145.         NotificationDetails(android: androidPlatformChannelSpecifics);
  146.     await flutterLocalNotificationsPlugin.show(
  147.       0,
  148.       'Outside Geofence',
  149.       'You are outside the geofence area.',
  150.       platformChannelSpecifics,
  151.     );
  152.     print('Outside geofence notification sent');
  153.   }
  154.  
  155.   @override
  156.   Widget build(BuildContext context) {
  157.     return Scaffold(
  158.       appBar: AppBar(
  159.         title: const Text("Simple Google Map"),
  160.         centerTitle: true,
  161.       ),
  162.       body: GoogleMap(
  163.         initialCameraPosition: CameraPosition(
  164.           target: currentLocation ?? destinationLocation,
  165.           zoom: 13,
  166.         ),
  167.         markers: _markers,
  168.         onMapCreated: (GoogleMapController controller) {
  169.           _controller.complete(controller);
  170.           addDestinationMarker();
  171.         },
  172.       ),
  173.     );
  174.   }
  175.  
  176.   @override
  177.   void dispose() {
  178.     _locationSubscription?.cancel();
  179.     super.dispose();
  180.   }
  181. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement