uniapp 实现定位到当前城市

uniapp 实现定位到当前城市

**

  1. 在uniapp 文档 uni.getLocation方法可以获取到当前位置 [https://uniapp.dcloud.io/api/location/location?id=getlocation]

  2. 在address地址信息说明 参数中的city 可以定位到当前城市,代码如下:
    location() { if (uni.getStorageSync('position') == '') { uni.getLocation({ geocode: true, type: 'wgs84', success: (res) => { console.log('位置是', res) var str = res.address.city this.position_index = str.slice(0, str.length - 1) // uni.setStorageSync('position', this.position_index) } }) } },

  3. 在HBuilder 运行时可以成功定位到当前城市,但是打包运行在app上面时定位就不出来了。

原因在哪里了?

  1. 在uniapp官方文档中的注意中写到:在这里插入图片描述
    HBuilder 自带了高德定位
    如果要配置Appkey,详见https://ask.dcloud.net.cn/article/29
    最后我采取的方法是用经纬度来转化城市
location() {
				var that = this
				var weidu = ''
				var jd = ''
				if (uni.getStorageSync('position') == '') {
					uni.getLocation({
						geocode: true,
						type: 'wgs84',
						success: (res) => {
							console.log('位置是', res)
							weidu = res.latitude
							jd = res.longitude
							uni.request({
								url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + weidu + ',' + jd + '&key=你自己在高德控制台申请的key&get_poi=0',
								success: function(res) {
									console.log('得到的信息是', res);
									console.log('当前位置的纬度3:' + weidu);
									console.log('当前位置的经度3:' + jd);
									var status = res.data.result.address_component.city
									var position = status.slice(0, status.length - 1)
									console.log('位置是顶呱呱', position)
									that.position_index = position
									uni.setStorageSync('position', that.position_index)
								}
							})
							// var str = res.address.city
							// this.position_index = str.slice(0, str.length - 1)
							// uni.setStorageSync('position', this.position_index)
						}
					})
				}

注意:

  1. key 是在高德控制台申请的key https://console.amap.com/dev/key/app
    2.location后面接的数值,用++拼接,不然拼接的就是字符串
    拼接的是数值:url: ‘https://apis.map.qq.com/ws/geocoder/v1/?location=’ + weidu + ‘,’ + jd + '&key…
    拼接字符串:url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=weidu,jd + '&key…

版权声明:本文为Adimstar原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。