Flutter 跳轉地圖軟件調起導航:百度、高德、騰訊、蘋果

一、說明

我們在應用開發中經常需要用到地圖定位或導航的功能,而集成該功能的方式總的來說分爲兩類:

第 1 類:App 集成導航功能

這種方式的優點是可以進行深度地圖定製,比如出行或外賣軟件會有自己的定製,上面會有司機或騎手的小圖標,但是集成開發成本也是比較高的。

第 2 類:跳轉第三方地圖軟件

這種方式是比較簡單的一種,把目的地傳給第三方導航軟件,比如百度地圖,它會爲你提供導航功能。這種方式開發成本低,可快速提供導航功能。

由於 Flutter 技術出來不久,普及率算不上很高,目前很多導航定位還未對其提供專門支持,如果想集成導航功能的話,開發成本非常高,所以我們會考慮用跳轉三方地圖軟件的方式實現導航功能。

二、實現步驟

第 1 步:添加插件

在 pubspec.yaml 文件中添加依賴插件:

url_launcher: ^5.4.2

第 2 步:iOS 配置 info.plist

<key>LSApplicationQueriesSchemes</key>
<array>
	<string>iosamap</string>
	<string>qqmap</string>
	<string>baidumap</string>
</array>

第 3 步:跳轉導航

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'alert_msg_util.dart';

class MapUtil {

  /// 高德地圖
  static Future<bool> gotoAMap(longitude, latitude) async {
    var url = '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';

    bool canLaunchUrl = await canLaunch(url);

    if (!canLaunchUrl) {
      ToastUtil.show('未檢測到高德地圖~');
      return false;
    }

    await launch(url);

    return true;
  }

  /// 騰訊地圖
  static Future<bool> gotoTencentMap(longitude, latitude) async {
    var url = 'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';
    bool canLaunchUrl = await canLaunch(url);

    if (!canLaunchUrl) {
      ToastUtil.show('未檢測到騰訊地圖~');
      return false;
    }

    await launch(url);

    return canLaunchUrl;
  }

  /// 百度地圖
  static Future<bool> gotoBaiduMap(longitude, latitude) async {
    var url = 'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';

    bool canLaunchUrl = await canLaunch(url);

    if (!canLaunchUrl) {
      ToastUtil.show('未檢測到百度地圖~');
      return false;
    }

    await launch(url);

    return canLaunchUrl;
  }

  /// 蘋果地圖
  static Future<bool> _gotoAppleMap(longitude, latitude) async {
    var url = 'http://maps.apple.com/?&daddr=$latitude,$longitude';

    bool canLaunchUrl = await canLaunch(url);

    if (!canLaunchUrl) {
      ToastUtil.show('打開失敗~');
      return false;
    }

    await launch(url);
  }
}

以上是我封裝的一個工具類,基本上可以拿來直接用,其中 toast 是我自己封裝的,你們可以去掉這部分代碼,然後用你們自己的方式通知用戶打開失敗。

三、注意

  1. 添加依賴庫後不要忘記點擊:Packages get。
  2. 要停止應用後重新運行安裝到手機,添加三方庫後只用 hot reload 是無法生效的。

四、參考

  1. 高德地圖官方文檔
  2. 騰訊地圖官方文檔
  3. 百度地圖官方文檔
  4. 蘋果地圖官方文檔

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章