使用url_launcher跳转到外部地图导航
Flutter版本 |
---|
1.22.0.stable |
在pubspec.yaml中添加插件
url_launcher: 5.7.10
新建一个 url_open_utils.dart文件,作为工具类。
import 'dart:io';
import 'package:url_launcher/url_launcher.dart';
import 'package:water_app/widget/base/base_tip.dart';
class URLOpenUtils {
/// 腾讯地图调用
static Future<bool> openTencentMap(double longitude, double latitude, {String address, bool showErr: true}) async {
String url = 'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=FN4BZ-6E33P-LFTDB-VRZ4C-NTP3Z-RVFFK&debug=true&to=${address ?? ''}';
if (Platform.isIOS)
url = Uri.encodeFull(url);
try {
if (await canLaunch(url) != null) {
await launch(url);
}
} on Exception catch(e) {
if (showErr)
showToastCommon('无法调起腾讯地图');
return false;
}
return true;
}
/// 高德地图调用
static Future<bool> openAmap(double longitude, double latitude, {String address, bool showErr: true}) async {
String url = '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2&poiname=${address ?? ''}';
if (Platform.isIOS)
url = Uri.encodeFull(url);
try {
if (await canLaunch(url) != null) {
await launch(url);
}
} on Exception catch(e) {
if (showErr)
showToastCommon('无法调起高德地图');
return false;
}
return true;
}
/// 百度地图
static Future<bool> openBaiduMap(double longitude, double latitude, {String address, bool showErr: true}) async {
String url = 'baidumap://map/direction?destination=name:${address ?? ''}|latlng:$latitude,$longitude&coord_type=bd09ll&mode=driving';
if (Platform.isIOS)
url = Uri.encodeFull(url);
try {
if (await canLaunch(url) != null) {
await launch(url);
}
} on Exception catch(e) {
if (showErr)
showToastCommon('无法调起高德地图');
return false;
}
return true;
}
/// 苹果地图
static Future<bool> openAppleMap(longitude, latitude, {String address, bool showErr: true}) async {
String url = 'http://maps.apple.com/?daddr=$latitude,$longitude&address=$address';
if (Platform.isIOS)
url = Uri.encodeFull(url);
try {
if (await canLaunch(url) != null) {
await launch(url);
}
} on Exception catch(e) {
if (showErr)
showToastCommon('无法调起高德地图');
return false;
}
return true;
}
static Future<bool> openMap(longitude, latitude, {String address, bool showErr: false}) async {
bool flag = true;
if (!await openAmap(longitude, latitude, address: address, showErr: showErr)) {
if (!await openBaiduMap(longitude, latitude, address: address, showErr: showErr)) {
if (!await openTencentMap(longitude, latitude, address: address, showErr: showErr)) {
// if (!await openAppleMap(longitude, latitude, address: address, showErr: showErr)) {
flag = false;
showToastCommon('无法调用地图应用,请安装高德,百度,腾讯任意一种地图应用');
// }
}
}
}
return flag;
}
}
顺便提一下封装成工具类的好处
- 减少大量的重复的代码
- 当这个第三方插件出现问题或者停止维护时,方便全局替换
其中 longitude代表经度,latitude代表纬度,address代表地理位置
这个工具类兼容了市面上主流了的地图打开方式,适用于Android iOS两大平台
补充说明
为了方便大家测试,给大家推荐一个网站 地图经纬度网站
这个网站可以根据地点获取经纬度