Flutter地理围栏功能插件geofencing_flutter_plugin的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter地理围栏功能插件geofencing_flutter_plugin的使用

geofencing_flutter_plugin 是一个扩展了 Woosmap Geofencing Mobile SDKs 功能的 Flutter 插件。它支持 iOS 和 Android 平台,允许开发者在应用中实现地理围栏功能。

支持平台

  • iOS
  • Android

模块和对象

  • GeofencingFlutterPlugin: 包含监控位置、区域和兴趣点的方法。
  • Location: 代表位置对象。
  • POI: 代表兴趣点。
  • Region: 代表地理区域/地理围栏。
  • GeofenceRegion: 在本地数据库中添加新区域时使用。

类型

  • ProfileSource: 表示跟踪配置文件来源,可以是 ProfileSource.localProfileSource.external
  • RegionType: 表示区域类型,可能值为 RegionType.circleRegionType.isochrone

使用方法

初始化插件

首先需要导入插件并创建实例:

import 'package:geofencing_flutter_plugin/geofencing_flutter_plugin.dart';

final geofencingFlutterPlugin = GeofencingFlutterPlugin();

检查和请求权限

在初始化 SDK 之前,必须请求所需的定位权限。

检查定位权限状态

Future<String?> returnVal = geofencingFlutterPlugin.getPermissionsStatus();

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: ${error.message}');
});

请求定位权限

bool background = true; // 设置为true以请求后台定位权限
Future<String?> returnVal = geofencingFlutterPlugin.requestPermissions(background);

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: ${error.message}');
});

初始化插件

通过调用 initialize 方法来初始化插件:

Map<String, String> woosmapSettings = {
    "privateKeyWoosmapAPI": "<<WOOSMAP_KEY>>",
    "trackingProfile": "liveTracking"
};

Future<String?> returnVal = geofencingFlutterPlugin.initialize(woosmapSettings);

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: $error');
});

开始和停止跟踪

一旦用户授权了定位权限,可以开始跟踪用户的位置:

// 开始跟踪
Future<String?> returnVal = geofencingFlutterPlugin.startTracking('liveTracking');

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: ${error.message}');
});

// 停止跟踪
Future<String?> returnVal = geofencingFlutterPlugin.stopTracking();

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: ${error.message}');
});

监听事件

可以通过监听位置和区域事件来获取更新:

监听位置

Future<String?> returnVal = geofencingFlutterPlugin.watchLocation();

returnVal.then((value) {
    // 获取位置流
    watchLocationStream = geofencingFlutterPlugin.getWatchLocationStream();
    // 监听流
    watchLocationStream.listen((location) {
        if (location != null) {
            debugPrint(location.locationDescription);
        } else {
            debugPrint("Location is null");
        }
    });
}).catchError((error) {
    debugPrint('An error occurred: $error');
});

监听区域

Future<String?> returnVal = geofencingFlutterPlugin.watchRegion();

returnVal.then((value) {
    // 获取区域流
    watchRegionStream = geofencingFlutterPlugin.getWatchRegionStream();
    // 监听流
    watchRegionStream.listen((region) {
        if (region != null) {
            debugPrint(region.eventName);
        } else {
            debugPrint("Region is null");
        }
    });
}).catchError((error) {
    debugPrint('An error occurred: $error');
});

添加和移除区域

创建自定义圆形区域

GeofenceRegion geofenceRegion = GeofenceRegion(
    '7F91369E-467C-4CBD-8D41-6509815C4780', 
    51.50998, 
    -0.1337, 
    180, 
    RegionType.circle
);

Future<String?> returnVal = geofencingFlutterPlugin.addRegion(geofenceRegion);

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: ${error.message}');
});

移除区域

Future<String?> returnVal = geofencingFlutterPlugin.removeRegions('7F91369E-467C-4CBD-8D41-6509815C4780');

returnVal.then((value) {
    debugPrint(value!);
}).catchError((error) {
    debugPrint('An error occurred: ${error.message}');
});

完整示例 Demo

以下是一个完整的示例 Demo,展示了如何使用 geofencing_flutter_plugin 实现基本的地理围栏功能:

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:geofencing_flutter_plugin/geofencing_flutter_plugin.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeoFencing Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: GeoFencingDemoWidget(),
    );
  }
}

class GeoFencingDemoWidget extends StatefulWidget {
  @override
  _GeoFencingDemoWidgetState createState() => _GeoFencingDemoWidgetState();
}

class _GeoFencingDemoWidgetState extends State<GeoFencingDemoWidget> {
  final GeofencingFlutterPlugin geofencingFlutterPlugin = GeofencingFlutterPlugin();

  @override
  void initState() {
    super.initState();
    initializePlugin();
  }

  Future<void> initializePlugin() async {
    Map<String, String> settings = {
      "privateKeyWoosmapAPI": "<<YOUR_WOOSMAP_API_KEY>>",
      "trackingProfile": "liveTracking"
    };

    await geofencingFlutterPlugin.initialize(settings);
    await geofencingFlutterPlugin.requestPermissions(true);
  }

  void startTracking() {
    geofencingFlutterPlugin.startTracking('liveTracking').then((value) {
      debugPrint('Tracking started: $value');
    }).catchError((error) {
      debugPrint('Error starting tracking: ${error.message}');
    });
  }

  void stopTracking() {
    geofencingFlutterPlugin.stopTracking().then((value) {
      debugPrint('Tracking stopped: $value');
    }).catchError((error) {
      debugPrint('Error stopping tracking: ${error.message}');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GeoFencing Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: startTracking,
              child: Text('Start Tracking'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: stopTracking,
              child: Text('Stop Tracking'),
            ),
          ],
        ),
      ),
    );
  }
}

这个示例展示了如何初始化插件、请求权限、开始和停止跟踪。您可以根据需要扩展此示例以实现更复杂的地理围栏功能。


更多关于Flutter地理围栏功能插件geofencing_flutter_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地理围栏功能插件geofencing_flutter_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 geofencing_flutter_plugin 的代码示例。这个插件允许你在 Flutter 应用中实现地理围栏功能。地理围栏功能允许应用监测设备是否进入或离开某个指定的地理区域。

首先,你需要在你的 pubspec.yaml 文件中添加 geofencing_flutter_plugin 依赖:

dependencies:
  flutter:
    sdk: flutter
  geofencing_flutter_plugin: ^latest_version  # 请替换为最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,在你的 Flutter 应用中实现地理围栏功能。以下是一个基本的示例:

import 'package:flutter/material.dart';
import 'package:geofencing_flutter_plugin/geofencing_flutter_plugin.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late GeofencingFlutterPlugin _geofencing;

  @override
  void initState() {
    super.initState();
    _geofencing = GeofencingFlutterPlugin();
    _initializeGeofencing();
  }

  Future<void> _initializeGeofencing() async {
    // 请求权限
    bool hasPermission = await _geofencing.checkPermission();
    if (!hasPermission) {
      bool requestPermission = await _geofencing.requestPermission();
      if (!requestPermission) {
        print("地理围栏权限被拒绝");
        return;
      }
    }

    // 添加地理围栏
    Geofence geofence = Geofence(
      id: "my_geofence",
      latitude: 37.7853889,
      longitude: -122.4056973,
      radius: 1000.0,
      transitionTypes: [Geofence.GEOFENCE_TRANSITION_ENTER, Geofence.GEOFENCE_TRANSITION_EXIT],
    );

    List<Geofence> geofences = [geofence];

    await _geofencing.addGeofences(geofences).then((_) {
      print("地理围栏添加成功");
    }).catchError((error) {
      print("添加地理围栏失败: $error");
    });

    // 监听地理围栏事件
    _geofencing.geofenceService.addGeofencingStatusListener((GeofencingEvent event) {
      if (event.geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
        print("进入地理围栏: ${event.geofenceId}");
      } else if (event.geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
        print("离开地理围栏: ${event.geofenceId}");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Geofencing Demo'),
        ),
        body: Center(
          child: Text('请检查控制台输出以查看地理围栏事件'),
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖添加

    • pubspec.yaml 中添加 geofencing_flutter_plugin 依赖。
  2. 权限请求

    • 使用 _geofencing.checkPermission() 检查权限。
    • 如果权限被拒绝,使用 _geofencing.requestPermission() 请求权限。
  3. 添加地理围栏

    • 创建一个 Geofence 对象,指定围栏的 ID、纬度、经度、半径和触发类型。
    • 使用 _geofencing.addGeofences(geofences) 添加围栏。
  4. 监听地理围栏事件

    • 使用 _geofencing.geofenceService.addGeofencingStatusListener 监听围栏事件,处理进入和离开围栏的情况。

请注意,在实际应用中,你需要处理更多的错误情况,并根据具体需求调整代码。此外,确保在 Android 和 iOS 上正确配置必要的权限和后台模式(例如,在 AndroidManifest.xml 和 Info.plist 中配置必要的权限)。

回到顶部