Flutter地图服务插件map4d_services的使用

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

Flutter地图服务插件map4d_services的使用

Map4D Services Flutter Pub Package

map4d_services 是一个用于在 iOS 和 Android 应用中集成 Map4D 服务的 Flutter 插件。

要求

  • Android SDK 21+
  • iOS 9.3+

安装

要在项目中使用此插件,请在 pubspec.yaml 文件中添加 map4d_services 作为依赖项:

dependencies:
  map4d_services: ^1.1.1

或者运行以下命令:

flutter pub add map4d_services

设置服务 API 密钥

服务 API 密钥是一个唯一标识符,用于验证与您的项目相关的请求以进行使用和计费。您必须至少有一个与您的项目关联的 API 密钥。

获取 API 密钥:Map4D 用户中心

Android

android/app/src/main/AndroidManifest.xml 中提供服务 API 密钥:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>
        <meta-data
            android:name="vn.map4d.services.ACCESS_KEY"
            android:value="YOUR_SERVICES_ACCESS_KEY"/>
    </application>
</manifest>

iOS

ios/Runner/Info.plist 中提供服务 API 密钥:

<key>Map4dServicesAccessKey</key>
<string>YOUR_SERVICES_ACCESS_KEY</string>

简单使用示例

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

void getPlaceDetail() async {
  MFServices.places
      .fetchPlaceDetail('5c88df71d2c05acd14848f9e')
      .then((detail) => {print('Place Detail: $detail')})
      .onError<MFServiceError>((error, stackTrace) =>
          {print('Place Detail Error: ${error.code}, ${error.message}')});
}

更多示例请参见 example 目录

文档

完整示例 Demo

以下是一个完整的 Flutter 示例应用程序,展示了如何使用 map4d_services 插件执行各种操作。

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

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  void _placeDetail() async {
    MFServices.places
        .fetchPlaceDetail('5c88df71d2c05acd14848f9e')
        .then((detail) => {print('Place Detail: $detail')})
        .onError<MFServiceError>((error, stackTrace) =>
            {print('Place Detail Error: ${error.code}, ${error.message}')});
  }

  void _autoSuggest() async {
    try {
      final places = await MFServices.places.fetchSuggestion(
        'Tam Giang',
        location: const MFLocationComponent(
            latitude: 16.575619, longitude: 107.530756),
        acronym: false,
      );
      print('Auto Suggest: $places');
    } on MFServiceError catch (error) {
      print('Auto Suggest Error: ${error.code}, ${error.message}');
    }
  }

  void _textSearch() async {
    final places = await MFServices.places.fetchTextSearch('abc',
        types: ['atm'],
        datetime: DateTime.now(),
        location: const MFLocationComponent(
            latitude: 16.075177, longitude: 108.220228));
    print('Text Search: $places');
  }

  void _nearbySearch() async {
    try {
      final places = await MFServices.places.fetchNearbySearch(
        const MFLocationComponent(latitude: 16.075177, longitude: 108.220228),
        20000,
        text: 'Sịa',
        types: ['point'],
        datetime: DateTime.now(),
      );
      print('Nearby Search: $places');
    } on MFServiceError catch (error) {
      print('Nearby Search Error: ${error.code}, ${error.message}');
    }
  }

  void _viewboxSearch() async {
    try {
      final places = await MFServices.places.fetchViewboxSearch(
        const MFViewboxComponent(
            southwest: MFLocationComponent(
                latitude: 16.056453967981348, longitude: 108.19387435913086),
            northeast: MFLocationComponent(
                latitude: 16.093031550262133, longitude: 108.25927734375)),
        text: 'a',
        types: ['atm'],
        datetime: DateTime.now(),
      );
      print('Viewbox Search: $places');
    } on MFServiceError catch (error) {
      print('Viewbox Search Error: ${error.code}, ${error.message}');
    }
  }

  void _geocode() async {
    try {
      final geos = await MFServices.places.fetchGeocode(
          location: const MFLocationComponent(
              latitude: 16.024634, longitude: 108.209217),
          address: '31 Lê Văn Duyệt',
          viewbox: const MFViewboxComponent(
              southwest: MFLocationComponent(
                  latitude: 16.056453967981348, longitude: 108.19387435913086),
              northeast: MFLocationComponent(
                  latitude: 16.093031550262133, longitude: 108.25927734375)));
      print('Geocode: $geos');
    } on MFServiceError catch (error) {
      print('Geocode Error: ${error.code}, ${error.message}');
    }
  }

  void _directions() async {
    List<MFRouteType> routeTypes = <MFRouteType>[
      MFRouteType.motorway,
      MFRouteType.tunnel
    ];
    List<MFLocationComponent> waypoints = <MFLocationComponent>[
      const MFLocationComponent(
          latitude: 16.081126855919138, longitude: 108.21412717916483)
    ];
    MFRouteRestriction restriction = MFRouteRestriction.restrictCircleArea(
        const MFLocationComponent(latitude: 16.080611, longitude: 108.218113),
        30,
        types: routeTypes);
    try {
      final directions = await MFServices.routes.fetchDirections(
          const MFLocationComponent(
              latitude: 16.08116088350121, longitude: 108.21979357460582),
          const MFLocationComponent(
              latitude: 16.08334260545329, longitude: 108.21651589082553),
          waypoints: waypoints,
          restriction: restriction);
      print('Directions: $directions');
    } on MFServiceError catch (error) {
      print('Directions Error: ${error.code}, ${error.message}');
    }
  }

  void _routeETA() async {
    List<MFRouteType> routeTypes = <MFRouteType>[
      MFRouteType.motorway,
      MFRouteType.tunnel
    ];
    List<MFLocationComponent> origins = <MFLocationComponent>[
      const MFLocationComponent(
          latitude: 16.039173, longitude: 108.210912, alias: "alias1"),
      const MFLocationComponent(
          latitude: 16.039402, longitude: 108.211080, alias: 'alias2')
    ];

    MFRouteRestriction restriction = MFRouteRestriction.restrictCircleArea(
        const MFLocationComponent(latitude: 16.044597, longitude: 108.217263),
        30,
        types: routeTypes);

    try {
      final etas = await MFServices.routes.fetchRouteETA(
          origins,
          const MFLocationComponent(
              latitude: 16.0825981, longitude: 108.2219887),
          restriction: restriction);
      print('ETAs: $etas');
    } on MFServiceError catch (error) {
      print('Route ETA Error: ${error.code}, ${error.message}');
    }
  }

  void _routeMatrix() async {
    List<MFRouteType> routeTypes = <MFRouteType>[
      MFRouteType.motorway,
      MFRouteType.tunnel
    ];
    List<MFLocationComponent> origins = <MFLocationComponent>[
      const MFLocationComponent(latitude: 16.024634, longitude: 108.209217),
      const MFLocationComponent(latitude: 16.0717664, longitude: 108.2236151)
    ];

    List<MFLocationComponent> destinations = <MFLocationComponent>[
      const MFLocationComponent(latitude: 16.0717664, longitude: 108.2236151),
      const MFLocationComponent(latitude: 16.06104, longitude: 108.2167)
    ];

    MFRouteRestriction restriction = MFRouteRestriction.restrictCircleArea(
        const MFLocationComponent(latitude: 16.080611, longitude: 108.218113),
        30,
        types: routeTypes);

    MFServices.routes
        .fetchDistanceMatrix(origins, destinations, restriction: restriction)
        .then((matrix) => print('Matrix: $matrix'))
        .onError<MFServiceError>((error, stackTrace) =>
            print('Matrix Error: ${error.code}, ${error.message}'));
  }

  void _routeGraph() async {
    List<MFRouteType> routeTypes = <MFRouteType>[
      MFRouteType.motorway,
      MFRouteType.tunnel
    ];
    List<MFLocationComponent> points = <MFLocationComponent>[
      const MFLocationComponent(
          latitude: 16.08116088350121, longitude: 108.21979357460582),
      const MFLocationComponent(
          latitude: 16.08334260545329, longitude: 108.21651589082553)
    ];
    MFRouteRestriction restriction = MFRouteRestriction.restrictCircleArea(
        const MFLocationComponent(latitude: 16.080611, longitude: 108.218113),
        30,
        types: routeTypes);
    try {
      final graph = await MFServices.routes
          .fetchGraphRoute(points, restriction: restriction);
      print('Graph: $graph');
    } on MFServiceError catch (error) {
      print('Graph Route Error: ${error.code}, ${error.message}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Map4D Services'),
        ),
        body: ListView(
          children: [
            ListTile(
              leading: const Icon(Icons.place),
              title: const Text('Place Detail'),
              onTap: _placeDetail,
            ),
            ListTile(
              leading: const Icon(Icons.place),
              title: const Text('Auto Suggest'),
              onTap: _autoSuggest,
            ),
            ListTile(
              leading: const Icon(Icons.place),
              title: const Text('Text Search'),
              onTap: _textSearch,
            ),
            ListTile(
              leading: const Icon(Icons.place),
              title: const Text('Nearby Search'),
              onTap: _nearbySearch,
            ),
            ListTile(
              leading: const Icon(Icons.place),
              title: const Text('Viewbox Search'),
              onTap: _viewboxSearch,
            ),
            ListTile(
              leading: const Icon(Icons.adjust),
              title: const Text('Geocode'),
              onTap: _geocode,
            ),
            ListTile(
              leading: const Icon(Icons.edit_road),
              title: const Text('Directions'),
              onTap: _directions,
            ),
            ListTile(
              leading: const Icon(Icons.edit_road),
              title: const Text('Route ETA'),
              onTap: _routeETA,
            ),
            ListTile(
              leading: const Icon(Icons.edit_road),
              title: const Text('Route Matrix'),
              onTap: _routeMatrix,
            ),
            ListTile(
              leading: const Icon(Icons.edit_road),
              title: const Text('Route Graph'),
              onTap: _routeGraph,
            ),
          ],
        ),
      ),
    );
  }
}

以上代码展示了如何在 Flutter 应用程序中使用 map4d_services 插件进行地点详情、自动建议、文本搜索、附近搜索、视窗搜索、地理编码、路线方向、路线 ETA、距离矩阵和图形路由等功能。


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

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用map4d_services插件的简单示例代码。这个插件允许你集成和使用Map4D地图服务。

首先,确保你的Flutter项目已经创建,并且你已经在pubspec.yaml文件中添加了map4d_services依赖。

dependencies:
  flutter:
    sdk: flutter
  map4d_services: ^最新版本号  # 替换为实际的最新版本号

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

接下来,你需要在你的Dart代码中导入map4d_services包,并配置地图。以下是一个简单的示例,展示如何在Flutter应用中显示Map4D地图。

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

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

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

class Map4DScreen extends StatefulWidget {
  @override
  _Map4DScreenState createState() => _Map4DScreenState();
}

class _Map4DScreenState extends State<Map4DScreen> {
  Map4DController? _map4DController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Map4D Map'),
      ),
      body: Stack(
        children: [
          Map4D(
            onMapCreated: (Map4DController controller) {
              _map4DController = controller;
              _moveToCenter();
            },
            apiKey: '你的Map4D API Key',  // 替换为你的Map4D API Key
            initialCameraPosition: CameraPosition(
              target: LatLng(10.763238, 106.680735), // 初始中心点,例如越南河内
              zoom: 14.0,
            ),
          ),
          // 你可以在这里添加其他覆盖层或标记
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_map4DController != null) {
            _moveToCenter();
          }
        },
        tooltip: 'Move to Center',
        child: Icon(Icons.my_location),
      ),
    );
  }

  void _moveToCenter() {
    _map4DController?.animateCamera(
      CameraUpdate.newLatLngZoom(
        LatLng(10.763238, 106.680735), // 目标位置
        14.0,
      ),
    );
  }
}

说明:

  1. 依赖管理:确保在pubspec.yaml中添加了map4d_services依赖。
  2. 导入包:在Dart文件中导入map4d_services包。
  3. 创建Map4D地图:使用Map4D小部件创建地图视图,并传入必要的参数,如API Key和初始相机位置。
  4. 地图控制:通过Map4DController控制地图,例如移动地图到特定位置。
  5. UI布局:使用ScaffoldStackFloatingActionButton创建简单的UI布局。

确保你已经在Map4D开发者平台注册并获取了API Key,并将其替换到代码中的apiKey字段。

这个示例展示了如何集成Map4D地图服务,并控制地图的基本操作。根据需求,你可以进一步扩展功能,例如添加标记、覆盖层、处理地图事件等。

回到顶部