前言:兄弟們,咱們這個基礎部分是已經結束了,學會之前的那些騷操作就基本上可以自己寫點小東西玩玩了,現在來講講一些開發中常用的功能,

定位是我們開發中常用的功能,為了幫助大家理解,我冒著生命危險從高德總部偷出來了這一份方案!!
(求大家給個三聯,我好跑路啊)
話不多說,先上效果圖:

準備階段:
1.插件準備:
amap_flutter_location: ^2.0.0 #高德地圖
插件地址
permission_handler: ^8.1.4 #權限管理,獲取定位權限用
插件地址
2.在高德的開發者平臺申請key:
第一步:注冊開發者賬號
高德開發者地址在這里

第二步:創建新的應用,并申請key

第三步:

關于如何獲取SHA1,以及處理高德定位使用中的報錯下一篇文章會詳細的講解
第四步獲取到key:

第五步:獲取自己需要的SDk

這樣準備步驟就完成了,
第一步:SDK與權限處理
SDK處理:
在app檔案夾下創建libs檔案夾,把下載的SDK放入

然后在build.gradle中配置SDK:
dependencies{
//添加demo中引入高德地圖SDK
implementation fileTree(include: ['*.zip'], dir: 'libs')
implementation('com.amap.api:location:5.2.0')
//定位功能
compile 'com.amap.api:location:latest.integration'
}
權限處理:
在這個檔案下配置:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--訪問網路-->
<uses-permission android:name="android.permission.INTERNET" />
<!--粗略定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!--精確定位-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--申請呼叫A-GPS模塊-->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<!--用于獲取運營商資訊,用于支持提供運營商資訊相關的介面-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--用于訪問wifi網路資訊,wifi資訊會用于進行網路定位-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--用于獲取wifi的獲取權限,wifi資訊會用來進行網路定位-->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!--用于讀取手機當前的狀態-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--用于寫入快取資料到擴展存盤卡-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
第二步:配置Key
仍在這個檔案中:

在application下:
meta-data
android:name="com.amap.api.v2.apikey"
android:value="//你自己的Key" />
<service android:name="com.amap.api.location.APSService"/> //定位
現在所有的配置都完成了!
第三步:代碼使用
代碼可以之間使用,放置文末了,只需要把自己的key替換一下
我們來看看官網的一些api:
定位結果是以map的形式回傳的,具體內容為
/// `callbackTime`:回呼時間,格式為"yyyy-MM-dd HH:mm:ss"
///
/// `locationTime`:定位時間, 格式為"yyyy-MM-dd HH:mm:ss"
///
/// `locationType`: 定位型別, 具體型別可以參考https://lbs.amap.com/api/android-location-sdk/guide/utilities/location-type
///
/// `latitude`:緯度
///
/// `longitude`:精度
///
/// `accuracy`:精確度
///
/// `altitude`:海拔, android上只有locationType==1時才會有值
///
/// `bearing`: 角度,android上只有locationType==1時才會有值
///
/// `speed`:速度, android上只有locationType==1時才會有值
///
/// `country`: 國家,android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `province`: 省,android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `city`: 城市,android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `district`: 城鎮(區),android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `street`: 街道,android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `streetNumber`: 門牌號,android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `cityCode`: 城市編碼,android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `adCode`: 區域編碼, android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `address`: 地址資訊, android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `description`: 位置語意, android上只有通過[AMapLocationOption.needAddress]為true時才有可能回傳值
///
/// `errorCode`: 錯誤碼,當定位失敗時才會回傳對應的錯誤碼, 具體錯誤請參考:https://lbs.amap.com/api/android-location-sdk/guide/utilities/errorcode
///
/// `errorInfo`: 錯誤資訊, 當定位失敗時才會回傳
詳細代碼:記得替換自己的Key哦!
import 'dart:async';
import 'dart:io';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
String _locationText;
class AmapPage extends StatefulWidget {
@override
_AmapPageState createState() => new _AmapPageState();
}
class _AmapPageState extends State<AmapPage> {
Map<String, Object> _locationResult;
StreamSubscription<Map<String, Object>> _locationListener;
AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();
@override
void initState() {
super.initState();
// 這個api是我在網上找的,必須用自己的,我的代碼里也是我自己去申請的,ios的可以先不申請,但是要寫,我的ios的key是用下面的這個
/// 動態申請定位權限
requestPermission();
AMapFlutterLocation.setApiKey(
"自己的key", "自己的key");
///設定Android和iOS的apiKey<br>
///
/// 定位Flutter插件提供了單獨的設定ApiKey的介面,
/// 使用介面的優先級高于通過Native配置ApiKey的優先級(通過Api介面配置后,通過Native組態檔設定的key將不生效),
/// 使用時可根據實際情況決定使用哪種方式
///
///key的申請請參考高德開放平臺官網說明<br>
///
///Android: https://lbs.amap.com/api/android-location-sdk/guide/create-project/get-key
///
///iOS: https://lbs.amap.com/api/ios-location-sdk/guide/create-project/get-key
///iOS 獲取native精度型別
if (Platform.isIOS) {
requestAccuracyAuthorization();
}
///注冊定位結果監聽
_locationListener = _locationPlugin
.onLocationChanged()
.listen((Map<String, Object> result) {
setState(() {
_locationResult = result;
print('定位結果${result}');
_locationText = ' ' +
_locationResult['province'] +
_locationResult['city'] +
_locationResult['district'] +
_locationResult['street'];
});
print('詳細資訊${_locationText}');
});
}
@override
void dispose() {
super.dispose();
///移除定位監聽
if (null != _locationListener) {
_locationListener.cancel();
}
///銷毀定位
if (null != _locationPlugin) {
_locationPlugin.destroy();
}
}
///設定定位引數
void _setLocationOption() {
if (null != _locationPlugin) {
AMapLocationOption locationOption = new AMapLocationOption();
///是否單次定位
locationOption.onceLocation = false;
///是否需要回傳逆地理資訊
locationOption.needAddress = true;
///逆地理資訊的語言型別
locationOption.geoLanguage = GeoLanguage.ZH;
locationOption.desiredLocationAccuracyAuthorizationMode =
AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;
locationOption.fullAccuracyPurposeKey = "AMapLocationScene";
///設定Android端連續定位的定位間隔
locationOption.locationInterval = 2000;
///設定Android端的定位模式<br>
///可選值:<br>
///<li>[AMapLocationMode.Battery_Saving]</li>
///<li>[AMapLocationMode.Device_Sensors]</li>
///<li>[AMapLocationMode.Hight_Accuracy]</li>
locationOption.locationMode = AMapLocationMode.Hight_Accuracy;
///設定iOS端的定位最小更新距離<br>
locationOption.distanceFilter = -1;
///設定iOS端期望的定位精度
/// 可選值:<br>
/// <li>[DesiredAccuracy.Best] 最高精度</li>
/// <li>[DesiredAccuracy.BestForNavigation] 適用于導航場景的高精度 </li>
/// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
/// <li>[DesiredAccuracy.Kilometer] 1000米</li>
/// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
locationOption.desiredAccuracy = DesiredAccuracy.Best;
///設定iOS端是否允許系統暫停定位
locationOption.pausesLocationUpdatesAutomatically = false;
///將定位引數設定給定位插件
_locationPlugin.setLocationOption(locationOption);
}
}
///開始定位
void _startLocation() {
if (null != _locationPlugin) {
///開始定位之前設定定位引數
_setLocationOption();
_locationPlugin.startLocation();
}
}
///停止定位
void _stopLocation() {
if (null != _locationPlugin) {
_locationPlugin.stopLocation();
}
}
Container _createButtonContainer() {
return new Container(
alignment: Alignment.center,
child: new Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new RaisedButton(
onPressed: _startLocation,
child: new Text('開始定位'),
color: Colors.blue,
textColor: Colors.white,
),
new Container(width: 20.0),
new RaisedButton(
onPressed: _stopLocation,
child: new Text('停止定位'),
color: Colors.blue,
textColor: Colors.white,
)
],
));
}
Widget _resultWidget(key, value) {
return new Container(
child: new Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
alignment: Alignment.centerRight,
width: 100.0,
child: new Text('$key :'),
),
new Container(width: 5.0),
new Flexible(child: new Text('$value', softWrap: true)),
],
),
);
}
@override
Widget build(BuildContext context) {
List<Widget> widgets = new List();
widgets.add(_createButtonContainer());
if (_locationResult != null) {
_locationResult.forEach((key, value) {
widgets.add(_resultWidget(key, value));
});
}
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: new Text('高德定位測驗'),
),
body: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: widgets,
),
));
}
///獲取iOS native的accuracyAuthorization型別
void requestAccuracyAuthorization() async {
AMapAccuracyAuthorization currentAccuracyAuthorization =
await _locationPlugin.getSystemAccuracyAuthorization();
if (currentAccuracyAuthorization ==
AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
print("精確定位型別");
} else if (currentAccuracyAuthorization ==
AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
print("模糊定位型別");
} else {
print("未知定位型別");
}
}
/// 動態申請定位權限
void requestPermission() async {
// 申請權限
bool hasLocationPermission = await requestLocationPermission();
if (hasLocationPermission) {
print("定位權限申請通過");
} else {
print("定位權限申請不通過");
}
}
/// 申請定位權限
/// 授予定位權限回傳true, 否則回傳false
Future<bool> requestLocationPermission() async {
//獲取當前的權限
var status = await Permission.location.status;
if (status == PermissionStatus.granted) {
//已經授權
return true;
} else {
//未授權則發起一次申請
status = await Permission.location.request();
if (status == PermissionStatus.granted) {
return true;
} else {
return false;
}
}
}
}
歡迎留言糾正 ~ 不妨給個點贊哈哈
我是阿T一個幽默的程式員 我們下期再見~
添加我為你的好友,領取原始碼以及Flutter學習資料~

加入我們吧,一起學習,一起進步~

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/292536.html
標籤:其他
上一篇:微信登錄實作-Android
