Flutter地图导航插件mapmyindia_direction_plugin的使用

Flutter 地图导航插件 mapmyindia_direction_plugin 的使用

概述

mapmyindia_direction_plugin 是一个用于在 Flutter 应用中展示路线的组件。它支持以下基本功能:

  • 使用 MapmyIndia 地址搜索来查找起点、终点和途经点。
  • 支持起点和终点使用 MapmyIndia 数字地址(分号分隔)或 WGS 84 地理坐标。
  • 可以设置车辆类型,如驾驶、骑行等。
  • 轻松设置交通和 ETA 信息。

更多详细信息,请联系 apisupport@mapmyindia.com

开始使用

要在 Flutter 项目中使用 mapmyindia_direction_plugin,首先需要将其添加到项目的 pubspec.yaml 文件中:

dependencies:
  mapmyindia_direction_plugin: ^0.2.0

然后在 Dart 代码中导入该包:

import 'package:mapmyindia_direction_plugin/mapmyindia_direction_plugin.dart';

添加 MapmyIndia 密钥

必须通过 MapmyIndiaAccountManager 类提供密钥。

MapmyIndiaAccountManager.setMapSDKKey(MAP_SDK_KEY);
MapmyIndiaAccountManager.setRestAPIKey(REST_API_KEY);
MapmyIndiaAccountManager.setAtlasClientId(ATLAS_CLIENT_ID);
MapmyIndiaAccountManager.setAtlasClientSecret(ATLAS_CLIENT_SECRET);

使用方向小部件

使用 openDirectionWidget 方法打开方向小部件:

// Platform messages may fail, so we use a try/catch PlatformException.
try {
  DirectionCallback directionCallback = await openDirectionWidget(directionOptions: options);
} on PlatformException {
  // Handle error
}

可以通过 DirectionOptions 设置小部件的属性:

DirectionOptions options = DirectionOptions(
  showStartNavigation: settings.showStartNavigation,
  showAlternative: settings.showAlternative,
  steps: settings.showSteps,
  resource: settings.resource,
  profile: settings.profile,
  overview: settings.overView,
  excludes: settings.excludes.length == 0 ? null : settings.excludes,
  searchPlaceOption: placeOptions,
  destination: settings.eloc != null
      ? DirectionPoint(
          settings.placeName!,
          settings.placeAddress!,
          eLoc: settings.eloc,
        )
      : settings.dLng != null && settings.dLat != null
          ? DirectionPoint(
              settings.placeName!,
              settings.placeAddress!,
              location: LatLng(
                double.parse(settings.dLat!),
                double.parse(settings.dLng!),
              ),
            )
          : null,
);

示例代码

以下是完整的示例代码:

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mapmyindia_direction_plugin_example/DirectionSettings.dart';
import 'package:mapmyindia_direction_plugin_example/settingWidget.dart';

import 'package:mapmyindia_gl/mapmyindia_gl.dart';
import 'package:mapmyindia_direction_plugin/mapmyindia_direction_plugin.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
    routes: <String, WidgetBuilder>{
      'SettingWidget': (BuildContext context) => SettingWidget(),
    },
  ));
}

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

class _MyAppState extends State<MyApp> {
  static const String MAP_SDK_KEY = "your_map_sdk_key";
  static const String REST_API_KEY = "your_rest_api_key";
  static const String ATLAS_CLIENT_ID = "your_atlas_client_id";
  static const String ATLAS_CLIENT_SECRET = "your_atlas_client_secret";

  DirectionCallback _directionCallback = DirectionCallback(null, null);

  [@override](/user/override)
  void initState() {
    super.initState();
    MapmyIndiaAccountManager.setMapSDKKey(MAP_SDK_KEY);
    MapmyIndiaAccountManager.setRestAPIKey(REST_API_KEY);
    MapmyIndiaAccountManager.setAtlasClientId(ATLAS_CLIENT_ID);
    MapmyIndiaAccountManager.setAtlasClientSecret(ATLAS_CLIENT_SECRET);
  }

  Future<void> openMapmyIndiaDirectionWidget() async {
    DirectionCallback directionCallback;
    DirectionSettings settings = DirectionSettings();
    PlaceOptions placeOptions = PlaceOptions(
      tokenizeAddress: settings.tokenizeAddress,
      saveHistory: settings.saveHistory,
      historyCount: settings.historyCount != null ? int.parse(settings.historyCount!) : null,
      backgroundColor: settings.backgroundColor,
      toolbarColor: settings.toolbarColor,
      toolbarTintColor: settings.toolbarTintColor,
      zoom: settings.zoom != null ? double.parse(settings.zoom!) : null,
      location: settings.longitude != null && settings.latitude != null
          ? LatLng(double.parse(settings.latitude!), double.parse(settings.longitude!))
          : null,
      filter: settings.filter != null ? settings.filter : null,
    );

    DirectionOptions options = DirectionOptions(
      showStartNavigation: settings.showStartNavigation,
      showAlternative: settings.showAlternative,
      steps: settings.showSteps,
      resource: settings.resource,
      profile: settings.profile,
      overview: settings.overView,
      excludes: settings.excludes.length == 0 ? null : settings.excludes,
      searchPlaceOption: placeOptions,
      destination: settings.eloc != null
          ? DirectionPoint(
              settings.placeName!,
              settings.placeAddress!,
              eLoc: settings.eloc,
            )
          : settings.dLng != null && settings.dLat != null
              ? DirectionPoint(
                  settings.placeName!,
                  settings.placeAddress!,
                  location: LatLng(
                    double.parse(settings.dLat!),
                    double.parse(settings.dLng!),
                  ),
                )
              : null,
    );

    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      directionCallback = await openDirectionWidget(directionOptions: options);
    } on PlatformException {
      directionCallback = DirectionCallback(null, null);
    }
    print(json.encode(directionCallback.directionResponse?.toMap()));

    if (!mounted) return;

    setState(() {
      _directionCallback = directionCallback;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Direction Example'),
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.settings,
                color: Colors.white,
              ),
              onPressed: () {
                Navigator.pushNamed(context, 'SettingWidget');
              },
            )
          ],
        ),
        body: Center(
          child: Column(children: [
            SizedBox(height: 20),
            Text(_directionCallback.selectedIndex == null
                ? 'Selected Index: '
                : 'Selected Index: ${_directionCallback.selectedIndex}'),
            SizedBox(height: 20),
            Text(_directionCallback.directionResponse?.waypoints == null
                ? 'Distance: '
                : 'Distance: ${_directionCallback.directionResponse?.routes?[0].distance}'),
            SizedBox(height: 20),
            Text(_directionCallback.directionResponse?.waypoints == null
                ? 'Duration: '
                : 'Duration: ${_directionCallback.directionResponse?.routes?[0].duration}'),
            SizedBox(height: 20),
            TextButton(
              child: Text('Open Direction Widget'),
              onPressed: () => openMapmyIndiaDirectionWidget(),
            )
          ]),
        ),
      ),
    );
  }
}

更多关于Flutter地图导航插件mapmyindia_direction_plugin的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter地图导航插件mapmyindia_direction_plugin的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


mapmyindia_direction_plugin 是一个用于在 Flutter 应用中集成 MapmyIndia 地图和导航功能的插件。以下是如何在 Flutter 项目中使用 mapmyindia_direction_plugin 的基本步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 mapmyindia_direction_plugin 依赖:

dependencies:
  flutter:
    sdk: flutter
  mapmyindia_direction_plugin: ^<latest_version>

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

2. 获取 API 密钥

在使用 MapmyIndia 服务之前,你需要在 MapmyIndia Developer Portal 注册并获取 API 密钥。

3. 初始化插件

在使用 mapmyindia_direction_plugin 之前,需要初始化插件并设置 API 密钥。通常,你可以在应用的 main.dart 文件中进行初始化:

import 'package:mapmyindia_direction_plugin/mapmyindia_direction_plugin.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize the plugin with your MapmyIndia API key
  await MapmyIndiaDirectionPlugin.initialize('<YOUR_MAPMYINDIA_API_KEY>');
  
  runApp(MyApp());
}

4. 使用方向导航功能

mapmyindia_direction_plugin 提供了获取方向、导航和路线规划的功能。以下是一个简单的示例,展示如何使用该插件获取两个地点之间的路线:

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

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

class _MapScreenState extends State<MapScreen> {
  String? routeResponse;

  Future<void> getRoute() async {
    try {
      // Define the origin and destination coordinates
      LatLng origin = LatLng(28.6129, 77.2295); // Example: Delhi
      LatLng destination = LatLng(28.7041, 77.1025); // Example: Noida

      // Get the route between origin and destination
      var response = await MapmyIndiaDirectionPlugin.getRoute(
        origin: origin,
        destination: destination,
        profiles: Profile.driving,
      );

      setState(() {
        routeResponse = response.toString();
      });
    } catch (e) {
      setState(() {
        routeResponse = 'Error: $e';
      });
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('MapmyIndia Direction Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: getRoute,
              child: Text('Get Route'),
            ),
            SizedBox(height: 20),
            Text(routeResponse ?? 'Press the button to get route'),
          ],
        ),
      ),
    );
  }
}
回到顶部