uniapp obtains the current location information in H5 without SDK and can directly obtain the city (including the longitude and latitude of the province, city and city code)

foreword

Recently, when I was trying to obtain the user's current location information, I found that the compatibility of uni.getLocation (OBJECT) officially provided by uniapp is not particularly good. There are a lot of precautions. In actual use scenarios, the effect is not ideal. Not very stable either. So I repackaged some things of Tencent Maps to improve the compatibility! Below I will explain the logic of the encapsulation ideas I use to everyone.

完整代码可私信我我发给你

insert image description here

Effect preview

insert image description here
insert image description here

Compatibility Note

insert image description here

Preparation

  1. Tencent map key
  2. Tencent map js file(可以找我要哈!!)

Logical thinking:

  1. Determine the environment and obtain location permission
  2. Create a Tencent map positioning instance for subsequent method calls
  3. Encapsulate the method of getLocation to obtain location information
  4. Provide watchPosition monitoring position and clearWatch stop monitoring method
  5. All methods are returned in the form of Promise, which is convenient for the caller to use.

step

1. Create a new utils folder, and install the Baidu js file under the folder

insert image description here

2. Create a new component file getlocation.vue in the file components

insert image description here

3. Encapsulate the specific logic code in the getlocation.vue component

3.1 Introduce the Tencent js file to initialize and judge the current environment and judge whether the user authorizes the location permission, and create a Tencent map instance, which is convenient for subsequent calls
            import './geolocation.min.js'
            
            init() {
    
    
				if (origin.indexOf('https') === -1) {
    
    
					uni.hideLoading()
					uni.showToast({
    
    
						title: '当前环境无法获取定位信息',
						icon: 'none',
						duration: 2000,
					});
					throw '请在 https 环境中使用本插件'
				}
				if (!navigator || !navigator.geolocation) {
    
    
					uni.hideLoading()
					uni.showToast({
    
    
						title: '当前环境无法获取定位信息',
						icon: 'none',
						duration: 2000,
					});

					throw '地理位置服务不可用'
				}

				const options = {
    
    
					enableHighAccuracy: true,
					timeout: 5000,
					maximumAge: 0
				};
				return new Promise((resolve, rejace) => {
    
    
					navigator.geolocation.getCurrentPosition((res) => {
    
    
						this.myMap = new qq.maps.Geolocation("你的key",
							"地图标点");
						resolve(this)
					}, rejace, options)
				})
			},

code 1 表示用户拒绝授权 code 3 未获取到地址信息,可能是设备没有开启定位服务或者系统没有给浏览器定位权限
【H5】 Obtaining latitude and longitude position navigator.geolocation.getCurrentPosition
navigator.geolocation.getCurrentPosition (function(){ }) parameter description:

Longitude: coords.longitude
Latitude: coords.latitude
Accuracy: coords.accuracy
Altitude: coords.altitude
Altitude Accuracy: coords.altitudeAcuracy
Direction of travel: coords.heading
Ground speed: coords.speed
Requested time: new Date(position.timestamp )

3.2 The method of encapsulating getLocation to obtain location information
			getLocation() {
    
    
				return new Promise((resolve, reject) => {
    
    
					this.myMap.getLocation(res => {
    
    
						resolve(res)
					}, err => {
    
    
						reject(err)
					})
				})
			},

4. How to use

<get_location ref='muLocation'></get_location>

import getLocation from '@/componentss/getlocation.vue'
components: {
    
    
  getLocation,
}


locationRef: null,


onLoad() {
    
    
//初始化权限,提示用户授权以及重新获取权限
			this.$nextTick(() => {
    
    
				uni.showLoading({
    
    
					title: '定位组件加载中...',
					mask: true
				})
				this.$refs.muLocation.init().then(location => {
    
    
					this.locationRef = location
					this.getLocationl();
					uni.hideLoading()
				}, err => {
    
    
					uni.hideLoading()
					if (err.code === 1) {
    
    
						uni.showModal({
    
    
							title: '获取定位权限失败',
							content: '你拒绝了位置授权服务。请允许当前页面获取定位授权,后刷新页面。'
						})
					} else {
    
    
						uni.showModal({
    
    
							title: '获取定位权限失败',
							content: '请确定手机定位已打开,并且当前浏览器允许获取定位,开启后请刷新页面。'
						})
					}
				})

			})
		},
          methods: {
    
    
            // 获取精准定位
			getLocationl() {
    
    
				let that = this
				if (!that.locationRef) return uni.showToast({
    
    
					title: '未授权位置获取',
					icon: 'none'
				})
				that.locationRef.getLocation()
					.then(res => {
    
    
				     	console.oog(res)
				     	//这里面写你自己的逻辑 res即为详细定位信息
						that.valiFormData.latitude = res.lat; //纬度
						that.valiFormData.longitude = res.lng; //经度
						that.valiFormData.areaNum = res.adcode;//市区code
						that.valiFormData.areaNumName = res.city;//市区
					})
			},
		}

Summarize

The above is based on the development of the uni-app framework, using Promise for asynchronous request and result return, and the packaged H5 to obtain the current detailed positioning information component. I hope everyone can communicate together.

Inspired by Mr. He Mumu

Guess you like

Origin blog.csdn.net/2303_76218115/article/details/130832204