微信小程序使用高德API获取位置信息

	//调用方法
	app.getAmapLocation().then((res) => {
		console.log(res);
	});
	var amapFile = require('static/js/amap-wx.js');
	varamap = new amapFile.AMapWX({
		key: '高德申请的key值'
	});
	//高德定位信息
	getAmapLocation(){
		let _this = this
		return new Promise((resolve, reject) => {
			amap.getRegeo({
				success: (res) => {
					//成功回调-----返回位置信息
					let data = res[0].regeocodeData;
					_this.uvData.province_name = data.addressComponent.province && data.addressComponent.province.length > 0 ? data.addressComponent.province : "";
					_this.uvData.city_name = data.addressComponent.city && data.addressComponent.city.length > 0 ? data.addressComponent.city : "";
					_this.uvData.area_name = data.addressComponent.district && data.addressComponent.district.length > 0 ? data.addressComponent.district : "";
					_this.uvData.address = data.formatted_address.replace(_this.uvData.province_name + _this.uvData.city_name + _this.uvData.area_name, '');
					_this.uvData.dimension = res[0].latitude ? res[0].latitude : "";
					_this.uvData.longitude = res[0].longitude ? res[0].longitude : "";
					wx.setStorageSync('gps', _this.uvData);
					resolve({
						type: 1,
						data: _this.uvData
					});
				},
				fail: (err) => {
					//失败回调
					console.log(err);
					if(err.errMsg== "getLocation:fail auth deny"){
						_this.checkAuth();
					}
					else if(err.errMsg== "getLocation:fail system permission denied" || err.errMsg== "getLocation:fail:ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF"){
						_this.showMsg('请检查手机定位开关或者微信App拥有有效的定位权限。');
					}else{
						_this.showMsg(err.errMsg);
					}
					resolve({
						type: 0,
						data: err
					});
				}
			})
		})
	},
	//检测定位设置
	checkAuth() { 
		const _this = this;
		wx.getSetting({
			success: res => {
				if (!res.authSetting['scope.userLocation'])
					_this.openConfirm();
			}
		})
	},
	//打开定位设置
	openConfirm() { 
		const _this = this;
		wx.showModal({
			content: '检测到您没有授权小程序定位权限,是否去设置打开?',
			confirmText: "确认",
			cancelText: "取消",
			success: function(res) {
				//点击“确认”时打开设置页面
				if (res.confirm) {
					wx.openSetting({
						success: (res) => {
							console.log(res, "定位设置回调")
							if(res.authSetting['scope.userLocation'] === true){
								_this.getAmapLocation();
							}else{
								_this.checkAuth();
							}
						}
					})
				} else {
					_this.checkAuth(); //强制定位-----不需要注释掉即可
				}
			}
		});
	},

你可能感兴趣的:(微信小程序,微信小程序,javascript,前端)