Flutter地理位置获取插件transport_gd_location的使用

Flutter地理位置获取插件transport_gd_location的使用

描述

transport_gd_location 是一个基于 Flutter 封装的网络货运信息交互系统位置信息上传插件,支持 iOS 和 Android 平台。该插件基于高德地图实现,旨在满足《交通运输部办公厅关于进一步做好网络平台道路货物运输信息化监测工作的通知》的要求。


使用步骤

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  transport_gd_location: ^版本号

然后运行以下命令安装依赖:

flutter pub get

2. 初始化插件

首先,需要调用 initSdk 方法初始化插件,并传入高德地图的 App Key。

Future<void> initSdk() async {
  bool success;
  try {
    success = await _transportGdLocationPlugin.initSdk(gdAppKey: "您的高德地图 App Key") ?? false;
  } on PlatformException {
    success = false;
  }
  print("初始化 - 结果 = $success");
}

3. 打开服务

通过 openService 方法打开位置信息上传服务。需要配置 ServiceConfig 参数,包括应用 ID、安全密钥、企业发送方代码和环境类型。

Future<void> openService() async {
  ResultModel? resultModel;
  try {
    ServiceConfig serviceConfig = ServiceConfig(
      appId: Platform.isAndroid
          ? "com.hswl.transport_gd_location.transport_gd_location_example"
          : "com.hswl.transportgdlocation.transportGdLocationExample",
      appSecurity: Platform.isAndroid
          ? "cd5a822984cd48c3a9a92c09e0868cb6b137e6bf336d456fa1b7696308449f05"
          : "fd6a81f2a41b4ea891269067e7eb4b68299ca62797ab4c348274f13d84d580bc",
      enterpriseSenderCode: "10002",
      environment: "debug",
    );
    resultModel = await _transportGdLocationPlugin.openService(serviceConfig: serviceConfig);
  } catch (e) {
    resultModel = null;
  }
  print("授权 - 结果 = ${resultModel?.toJson()}");
}

4. 示例代码

以下是一个完整的示例代码,展示了如何初始化插件并打开服务:

import 'dart:io';

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

import 'package:flutter/services.dart';
import 'package:transport_gd_location/transport_gd_location.dart';

import 'package:transport_gd_location/model/result_model.dart';
import 'package:transport_gd_location/model/service_config.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _transportGdLocationPlugin = TransportGdLocation();

  [@override](/user/override)
  void initState() {
    super.initState();
    initSdk();
  }

  // 初始化插件
  Future<void> initSdk() async {
    bool success;
    try {
      success = await _transportGdLocationPlugin.initSdk(gdAppKey: "您的高德地图 App Key") ?? false;
    } on PlatformException {
      success = false;
    }
    print("初始化 - 结果 = $success");
  }

  // 打开服务
  Future<void> openService() async {
    ResultModel? resultModel;
    try {
      ServiceConfig serviceConfig = ServiceConfig(
        appId: Platform.isAndroid
            ? "com.hswl.transport_gd_location.transport_gd_location_example"
            : "com.hswl.transportgdlocation.transportGdLocationExample",
        appSecurity: Platform.isAndroid
            ? "cd5a822984cd48c3a9a92c09e0868cb6b137e6bf336d456fa1b7696308449f05"
            : "fd6a81f2a41b4ea891269067e7eb4b68299ca62797ab4c348274f13d84d580bc",
        enterpriseSenderCode: "10002",
        environment: "debug",
      );
      resultModel = await _transportGdLocationPlugin.openService(serviceConfig: serviceConfig);
    } catch (e) {
      resultModel = null;
    }
    print("授权 - 结果 = ${resultModel?.toJson()}");
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Running on: $_platformVersion\n'),
        ),
      ),
    );
  }
}
1 回复

更多关于Flutter地理位置获取插件transport_gd_location的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


transport_gd_location 是一个用于在 Flutter 应用中获取地理位置的插件,它基于高德地图(AMap)的定位服务。使用这个插件,你可以轻松地在应用中获取设备的当前位置信息。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  transport_gd_location: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 配置高德地图

在使用 transport_gd_location 之前,你需要在高德开放平台注册一个应用,并获取一个 API Key。

Android 配置

android/app/src/main/AndroidManifest.xml 文件中添加以下配置:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <application
        android:name=".MyApplication"
        android:label="Your App"
        android:icon="@mipmap/ic_launcher">

        <!-- 高德地图 API Key -->
        <meta-data
            android:name="com.amap.api.v2.apikey"
            android:value="YOUR_AMAP_API_KEY" />

    </application>
</manifest>

iOS 配置

ios/Runner/Info.plist 文件中添加以下配置:

<key>NSLocationWhenInUseUsageDescription</key>
<string>我们需要获取您的位置信息以提供更好的服务</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>我们需要获取您的位置信息以提供更好的服务</string>
<key>AMapApiKey</key>
<string>YOUR_AMAP_API_KEY</string>

3. 使用插件获取位置

在你的 Flutter 代码中,你可以使用 transport_gd_location 插件来获取设备的位置信息。

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

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

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LocationScreen(),
    );
  }
}

class LocationScreen extends StatefulWidget {
  [@override](/user/override)
  _LocationScreenState createState() => _LocationScreenState();
}

class _LocationScreenState extends State<LocationScreen> {
  String _locationInfo = 'Unknown';

  Future<void> _getLocation() async {
    try {
      TransportGdLocation location = TransportGdLocation();
      LocationResult result = await location.getLocation();
      setState(() {
        _locationInfo = 'Latitude: ${result.latitude}, Longitude: ${result.longitude}';
      });
    } catch (e) {
      setState(() {
        _locationInfo = 'Failed to get location: $e';
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Location Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_locationInfo),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _getLocation,
              child: Text('Get Location'),
            ),
          ],
        ),
      ),
    );
  }
}
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!