uniapp实时获取当前位置

首先我们需要先下载一个插件(高德地图官网插件)

(插件主要作用是获取当前地理定位或者是自身的位置,并且可以返回名称name)

相关下载-微信小程序插件 | 高德地图API (amap.com)icon-default.png?t=N7T8https://developer.amap.com/api/wx/download

结合uniapp官网的示例一起使用,

在script中开头写

import amap from '../../common/amap-wx.130.js'

点击事件部分

			getWarpweft() {
			  const that = this;
			  that.po_tips = '定位中...';
		// 
		   
		
		
		// 
			  uni.getLocation({
			    type: 'wgs84', // 或 'gcj02'
			    success(res) {
			      console.log('定位成功', res);
			      that.po_tips = '重新定位';
			
			      const latitude = res.latitude;
			      const longitude = res.longitude;
			
			      // 调用逆地理编码方法获取地名
			      var myAmapFun = new amap.AMapWX({key:'ddb2a654bf6582459b81243b3bc45548'});
			      myAmapFun.getRegeo({
			      	location:longitude +','+latitude,
			        success: function(data){
			      	  // console.log(data[0],99);
					  // that.position = data[0].regeocodeData.addressComponent.city;
					   that.position = data[0].regeocodeData.addressComponent;
			      	  console.log(data[0].regeocodeData.addressComponent.city,99);
			          //成功回调
			        },
			        fail: function(info){
			          //失败回调
			          console.log(info)
			        }
			      })
			    },
			    fail(err) {
			      console.log('定位失败', err);
			      that.po_tips = '定位失败';
			      // 处理定位失败的情况,例如提示用户或执行其他操作
			    },
			  });
			}

data部分

po_tips: '重新定位',

position: '', //定位获取的位置


 

html部分

				<view class="dingwei">
					    <text>当前位置地名:{
   
   { currentAddress }}</text>
					 
				
					<view class="dingwei_city">
						<view class="dingwei_city_one" @tap="back_city(position,true)">
							{
   
   {position?position.city:'定位失败'}}
						</view>
						<view class="bold blue fmiddle" @click="getWarpweft"> 
							<text>{
   
   {po_tips}}</text>
						</view>
					</view>
				</view>

猜你喜欢

转载自blog.csdn.net/A12536365214/article/details/133095811