Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:math';
- import 'package:flutter/material.dart';
- import 'package:google_maps_flutter/google_maps_flutter.dart';
- import 'package:location/location.dart';
- import 'package:flutter_local_notifications/flutter_local_notifications.dart';
- class SimpleMap extends StatefulWidget {
- const SimpleMap({super.key});
- @override
- State<SimpleMap> createState() => _SimpleMapState();
- }
- class _SimpleMapState extends State<SimpleMap> {
- final LatLng destinationLocation = LatLng(-1.9501, 30.0589); // Example coordinates for KK 561 St
- final Completer<GoogleMapController> _controller = Completer();
- Set<Marker> _markers = {}; // Initialize an empty set of markers
- LatLng? currentLocation; // Assuming you have a way to get the current location
- Location location = Location();
- StreamSubscription<LocationData>? _locationSubscription;
- bool _notificationSentOutSide = false;
- bool _notificationSentInSide = false;
- FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
- @override
- void initState() {
- super.initState();
- _initializeNotifications();
- getCurrentLocation();
- }
- void _initializeNotifications() {
- const AndroidInitializationSettings initializationSettingsAndroid =
- AndroidInitializationSettings('@mipmap/ic_launcher');
- final InitializationSettings initializationSettings = InitializationSettings(
- android: initializationSettingsAndroid,
- );
- flutterLocalNotificationsPlugin.initialize(initializationSettings);
- }
- void getCurrentLocation() async {
- currentLocation = await location.getLocation().then((value) {
- currentLocation = LatLng(value.latitude!, value.longitude!);
- addCurrentLocMarker(currentLocation!);
- return currentLocation;
- });
- _locationSubscription = location.onLocationChanged.listen((newLoc) {
- setState(() {
- currentLocation = LatLng(newLoc.latitude!, newLoc.longitude!);
- addCurrentLocMarker(currentLocation!);
- _checkGeofenceStatus(newLoc.latitude!, newLoc.longitude!);
- });
- });
- }
- void addCurrentLocMarker(LatLng location) {
- Marker currentLocMarker = Marker(
- markerId: MarkerId('currentLocation'),
- icon: BitmapDescriptor.defaultMarker,
- position: location,
- infoWindow: InfoWindow(title: 'Current Location', snippet: 'You are here'),
- );
- setState(() {
- _markers.add(currentLocMarker);
- });
- }
- void addDestinationMarker() {
- Marker destinationMarker = Marker(
- markerId: MarkerId('destinationLocation'),
- icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
- position: destinationLocation,
- infoWindow: InfoWindow(title: 'Destination Location', snippet: 'Destination location...'),
- );
- setState(() {
- _markers.add(destinationMarker);
- });
- }
- void _checkGeofenceStatus(double latitude, double longitude) {
- bool insideGeofence = _isLocationInsideGeofence(latitude, longitude);
- if (insideGeofence && !_notificationSentInSide) {
- _triggerInSideNotification();
- _notificationSentInSide = true;
- _notificationSentOutSide = false;
- } else if (!insideGeofence && !_notificationSentOutSide) {
- _triggerOutSideNotification();
- _notificationSentOutSide = true;
- _notificationSentInSide = false;
- }
- }
- bool _isLocationInsideGeofence(double latitude, double longitude) {
- // Define your geofence boundaries, for example, a 500m radius around the destination
- double radiusInMeters = 500.0;
- double distance = _calculateDistance(latitude, longitude, destinationLocation.latitude, destinationLocation.longitude);
- return distance <= radiusInMeters;
- }
- double _calculateDistance(double lat1, double lon1, double lat2, double lon2) {
- const double p = 0.017453292519943295; // PI / 180
- final double a = 0.5 -
- cos((lat2 - lat1) * p) / 2 +
- cos(lat1 * p) * cos(lat2 * p) *
- (1 - cos((lon2 - lon1) * p)) / 2;
- return 12742 * asin(sqrt(a)) * 1000; // 2 * R; R = 6371 km
- }
- Future<void> _triggerInSideNotification() async {
- const AndroidNotificationDetails androidPlatformChannelSpecifics =
- AndroidNotificationDetails(
- 'geo_fence_channel',
- 'Geofence Notifications',
- importance: Importance.max,
- priority: Priority.high,
- );
- const NotificationDetails platformChannelSpecifics =
- NotificationDetails(android: androidPlatformChannelSpecifics);
- await flutterLocalNotificationsPlugin.show(
- 0,
- 'Inside Geofence',
- 'You are inside the geofence area.',
- platformChannelSpecifics,
- );
- print('Inside geofence notification sent');
- }
- Future<void> _triggerOutSideNotification() async {
- const AndroidNotificationDetails androidPlatformChannelSpecifics =
- AndroidNotificationDetails(
- 'geo_fence_channel',
- 'Geofence Notifications',
- importance: Importance.max,
- priority: Priority.high,
- );
- const NotificationDetails platformChannelSpecifics =
- NotificationDetails(android: androidPlatformChannelSpecifics);
- await flutterLocalNotificationsPlugin.show(
- 0,
- 'Outside Geofence',
- 'You are outside the geofence area.',
- platformChannelSpecifics,
- );
- print('Outside geofence notification sent');
- }
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: const Text("Simple Google Map"),
- centerTitle: true,
- ),
- body: GoogleMap(
- initialCameraPosition: CameraPosition(
- target: currentLocation ?? destinationLocation,
- zoom: 13,
- ),
- markers: _markers,
- onMapCreated: (GoogleMapController controller) {
- _controller.complete(controller);
- addDestinationMarker();
- },
- ),
- );
- }
- @override
- void dispose() {
- _locationSubscription?.cancel();
- super.dispose();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement