<template>
	<view class="content">
		<view style="text-align: center;">------权限-------</view>
		<button type="primary" @click="isProviderEnabled">GPS是否开启(android)</button>
		<button type="primary" @click="gotoLocationSetting">跳转定位设置页面</button>
		<button type="primary" @click="judgePermission">获取权限状态(ios)</button>
		<button type="primary" @click="requestPermission">请求权限(ios)</button>

		<view style="text-align: center;">------andorid位置提供者-------</view>
		<button type="primary" @click="getProviders">获取可用位置提供者(android)</button>
		<button type="primary" @click="getAllProviders">获取所有位置提供者(android)</button>
		<button type="primary" @click="getBestProvider">获取最佳的位置提供者(android)</button>

		<view style="text-align: center;">------定位-------</view>
		<button type="primary" @click="getLastKnownLocation">获取最新位置(android)</button>
		<button type="primary" @click="requestLocation">单次定位(ios)</button>
		<button type="primary" @click="startUpdatingLocation">开始持续定位</button>
		<view class="json">{{startUpdatingLocationJson}}</view>
		<button type="primary" @click="stopUpdatingLocation">取消持续定位</button>

		<view style="text-align: center;">------正反地理编码-------</view>
		<button type="primary" @click="reverseGeocode">反地理编码</button>
		<view class="json">{{reverseGeocodeJson}}</view>
		<button type="primary" @click="reverseGeocodeV2">反地理编码V2(andorid),不受google服务影响</button>
		<view class="json">{{reverseGeocodeV2Json}}</view>
		<button type="primary" @click="geocode">地理编码</button>
		<view class="json">{{geocodeJson}}</view>

		<view style="text-align: center;">------以下方法andorid7.0以上才支持-------</view>
		<button type="primary" @click="registerGnssStatus">注册监听卫星信息(GNSS处理后信息)</button>
		<view class="json">{{registerGnssStatusJson}}</view>
		<button type="primary" @click="unregisterGnssStatus">取消注册监听卫星信息</button>
		<button type="primary" @click="registerGnssMeasurements">注册监听卫星信息(GNSS测量原始信息)</button>
		<view class="json">{{registerGnssMeasurementsJson}}</view>
		<button type="primary" @click="unregisterGnssMeasurements">取消注册监听卫星信息</button>
	</view>
</template>

<script>
	var KJGNSS = uni.requireNativePlugin("KJ-GNSS");
	export default {
		data() {
			return {
				startUpdatingLocationJson: "",
				reverseGeocodeJson: "",
				reverseGeocodeV2Json: "",
				geocodeJson: "",
				registerGnssStatusJson: "",
				registerGnssMeasurementsJson: ""
			}
		},
		onLoad() {
			if (plus.os.name == 'Android') {
				plus.android.requestPermissions(
					['android.permission.ACCESS_FINE_LOCATION',
						'android.permission.ACCESS_COARSE_LOCATION'
					],
					function(resultObj) {
						var result = 0;
						for (var i = 0; i < resultObj.granted.length; i++) {
							var grantedPermission = resultObj.granted[i];
							console.log('已获取的权限：' + grantedPermission);
							result = 1
						}
						for (var i = 0; i < resultObj.deniedPresent.length; i++) {
							var deniedPresentPermission = resultObj.deniedPresent[i];
							console.log('拒绝本次申请的权限：' + deniedPresentPermission);
							result = 0
						}
						for (var i = 0; i < resultObj.deniedAlways.length; i++) {
							var deniedAlwaysPermission = resultObj.deniedAlways[i];
							console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
							result = -1
						}
					},
					function(error) {
						console.log('申请权限错误：' + error.code + " = " + error.message);
					}
				);
			}
		},
		methods: {
			isProviderEnabled() {
				var dic = {
					"provider": "gps" //位置提供者
				}
				KJGNSS.isProviderEnabled(dic, (res) => {
					console.log("isProviderEnabled:" + JSON.stringify(res));
				});
			},
			gotoLocationSetting() {
				KJGNSS.gotoLocationSetting();
			},
			judgePermission() {
				KJGNSS.judgePermission((res) => {
					console.log("judgePermission:" + JSON.stringify(res));
				});
			},
			requestPermission() {
				KJGNSS.requestPermission((res) => {
					console.log("requestPermission:" + JSON.stringify(res));
				});
			},
			getProviders() {
				var dic = {
					"enabledOnly": true //表示仅获取可用的位置提供者
				}
				KJGNSS.getProviders(dic, (res) => {
					console.log("getProviders:" + JSON.stringify(res));
				});
			},
			getAllProviders() {
				KJGNSS.getAllProviders((res) => {
					console.log("getAllProviders:" + JSON.stringify(res));
				});
			},
			getBestProvider() {
				var dic = {
					"accuracy": 2, //表示纬度和经度的理想精度  1-精度低，误差大于500米 2-精度中等，误差在100米到500米之间 3-精度高，误差小于100米
					//"bearingAccuracy":2,//指示所需的轴承精度 
					//"horizontalAccuracy":2,//指示所需的水平精度（经度和纬度）
					//"speedAccuracy":2,//指示所需的速度准确度
					//"verticalAccuracy":2,//指示所需的垂直精度（高度）
					"powerRequirement": 1, //对电源的需求 1-耗电低 2-耗电中等 3-耗电高
					"altitudeRequired": false, //指示提供者是否必须提供海拔信息
					"bearingRequired": false, //指示提供者是否必须提供方位信息
					"costAllowed": false, //指示提供者是否被允许产生货币成本
					"speedRequired": false, //指示提供者是否必须提供速度信
					"enabledOnly": true //表示仅获取可用的位置提供者
				}
				KJGNSS.getBestProvider(dic, (res) => {
					console.log("getBestProvider:" + JSON.stringify(res));
				});
			},
			getLastKnownLocation() {
				var dic = {
					"provider": "gps" //位置提供者
				}
				// KJGNSS.getLastKnownLocation(dic, (res) => {
				// 	console.log("getLastKnownLocation:" + JSON.stringify(res));
				// });
				let KJGNS = uni.requireNativePlugin("KJ-GNSS");
				console.log(KJGNS)
			},
			requestLocation() {
				var dic = {
					"desiredAccuracy": 1,
					"distanceFilter": 10,
					"allowsBackgroundLocationUpdates": true,
					"showsBackgroundLocationIndicator": true,
					"pausesLocationUpdatesAutomatically": false
				}
				KJGNSS.requestLocation(dic, (res) => {
					console.log("requestLocation:" + JSON.stringify(res));

				});
			},
			startUpdatingLocation() {
				var dic;
				if (plus.os.name == 'Android') {
					dic = {
						"providers": ["gps", "network", "passive"], //位置提供者数组，优先gps
						"minTime": 1000, //更新的最小时间
						"minDistance": 1 //更新的最小距离
					}
				} else {
					dic = {
						"isSingleLocation": false,
						"desiredAccuracy": "Best", //BestForNavigation(最精准) Best(最好的,米级) NearestTenMeters(十米) HundredMeters(百米) Kilometer(一公里) ThreeKilometers(三公里)
						"distanceFilter": 10, //刷新距离
						"allowsBackgroundLocationUpdates": false, //是否开启后台定位，为true 需要配置manifest.json->App常用其它设置->后台运行能力 location
						"showsBackgroundLocationIndicator": false, //是否显示后台定位提示(状态栏蓝色背景)
						"pausesLocationUpdatesAutomatically": false //定位是否会被系统自动暂停
					}
				}
				KJGNSS.startUpdatingLocation(dic, (res) => {
					console.log("startUpdatingLocation:" + JSON.stringify(res));
					this.startUpdatingLocationJson = JSON.stringify(res)
					if (plus.os.name == 'Android') {
						//返回参数说明参考：https://www.xfqiao.com/api/android-zh/android/location/Location.html
						/**
						 * {"method":"onLocationChanged","result":{"longitude":113.281456,"time":1687341181822,"hasBearing":false,"accuracy":40,"elapsedRealtimeNanos":1239298029066278,"provider":"network",
						 * "hasAccuracy":true,"bearing":0,"isFromMockProvider":false,"hasSpeed":false,"latitude":23.07654,"speed":0,"hasAltitude":false,"altitude":0}}
						 * isFromMockProvider - 如果位置来自模拟提供者，则返回true。
						 * */
						if (res.method == "onLocationChanged") {
							this.reverseGeocode(res.result.latitude, res.result.longitude)
							this.reverseGeocodeV2(res.result.latitude, res.result.longitude)
						}
					} else {
						/**
						 * {"result":[{"course":-1,"speed":-1,"longitude":113.2814133388547,"horizontalAccuracy":43,
						 * "timestamp":"2023-06-21 18:01:04","latitude":23.076741614788542,"courseAccuracy":-1,
						 * "ellipsoidalAltitude":1.8153233528137207,"altitude":8.372057914733887,"speedAccuracy":-1}]}
						 * course - 航向 位置的路线（以正北度数为单位）。如果无效，则为否定。0.0-359.9度，0为正北
						 * horizontalAccuracy - 水平的准确度（负数无效）
						 * ellipsoidalAltitude - WGS 84参考系下位置的椭球高度
						 * courseAccuracy - 航向精度（以度为单位）。如果无效，则返回负数。
						 * altitude - 海拔高度 可以是正（海平面以上）或负（海平面以下）
						 * speed - 速度 单位为m/s。如果速度无效，则为负数。
						 * speedAccuracy - 速度精度 单位为m/s。如果无效，则返回-1
						 * */
						var arr = res.result;
						var dic = arr[arr.length - 1];
						this.reverseGeocode(dic.latitude, dic.longitude)
					}
				});
			},
			stopUpdatingLocation() {
				KJGNSS.stopUpdatingLocation();
			},
			reverseGeocode(latitude, longitude) {
				var dic = {
					"latitude": latitude,
					"longitude": longitude,
					"maxResults": 1 //最大返回的结果，andorid才有
				}
				KJGNSS.reverseGeocode(dic, (res) => {
					console.log("reverseGeocode:" + JSON.stringify(res));
					this.reverseGeocodeJson = JSON.stringify(res)
					var arr = res.result;
					var dic = arr[arr.length - 1];
					this.geocode(dic.adminArea + dic.locality + dic.subLocality + dic.fetFeatureName);
				});
			},
			reverseGeocodeV2(latitude, longitude) {
				var dic = {
					"latitude": latitude,
					"longitude": longitude,
				}
				KJGNSS.reverseGeocodeV2(dic, (res) => {
					console.log("reverseGeocodeV2:" + JSON.stringify(res));
					this.reverseGeocodeV2Json = JSON.stringify(res)
				});
			},
			geocode(address) {
				var dic = {
					"address": address,
					"maxResults": 1 //最大返回的结果，andorid才有
				}
				KJGNSS.geocode(dic, (res) => {
					console.log("geocode:" + JSON.stringify(res));
					this.geocodeJson = JSON.stringify(res)
				});
			},
			registerGnssStatus() {
				KJGNSS.registerGnssStatus((res) => {
					console.log("registerGnssStatus:" + JSON.stringify(res));
					//返回参数说明参考：https://www.xfqiao.com/api/android-zh/android/location/GnssStatus.html
					this.registerGnssStatusJson = JSON.stringify(res)
				});
			},
			unregisterGnssStatus() {
				KJGNSS.unregisterGnssStatus();
			},
			registerGnssMeasurements() {
				KJGNSS.registerGnssMeasurements((res) => {
					console.log("registerGnssMeasurements:" + JSON.stringify(res));
					//返回参数说明参考：https://www.xfqiao.com/api/android-zh/android/location/GnssMeasurementsEvent.html
					this.registerGnssMeasurementsJson = JSON.stringify(res)
				});
			},
			unregisterGnssMeasurements() {
				KJGNSS.unregisterGnssMeasurements();
			}
		}
	}
</script>
<style>
	button {
		font-size: 15px
	}

	.json {
		word-wrap: break-word;
	}
</style>