首先展示一下效果图:(文章末尾放置官网链接和api链接)
其次展示一下代码结构:
html:
<view class="box">
<map id="map" show-location :scale="scale" style="width: 100%;height: 100%;" :latitude="latitude"
:longitude="longitude" :circles="circles" :markers="markers"> </map>
<view class="home-icon" @click="backMyLocation">
<u-icon name="home" color="#000" size="28px"></u-icon>
<text style="font-size: 12px;">我的位置</text>
</view>
<view class="targetIcon home-icon" @click="backTargetLocation">
<u-icon name="map" color="#000" size="28px"></u-icon>
<text style="font-size: 12px;">打卡位置</text>
</view>
<view class="refresh home-icon" @click="refresh">
<u-icon name="reload" color="#000" size="28px"></u-icon>
<text style="font-size: 12px;">刷新</text>
</view>
</view>
js:获取当前位置刷新(其中的markers就是小程序的标记属性)
getLocation() {
uni.showLoading({
title: '定位中...',
mask: true,
})
return new Promise((resolve, reject) => {
const _locationChangeFn = (res) => {
uni.hideLoading()
this.markers[1].latitude = res.latitude
this.markers[1].longitude = res.longitude
this.myLatitude = res.latitude
this.myLongitude = res.longitude
resolve(res)
wx.offLocationChange(_locationChangeFn)
wx.stopLocationUpdate(_locationChangeFn);
}
wx.startLocationUpdate({
success: (res) => {
wx.onLocationChange(_locationChangeFn)
},
fail: (err) => {
reject(err)
},
})
})
},
回到我当前的位置:
backMyLocation() {
// this.latitude = this.myLatitude
// this.longitude = this.myLongitude
const mapCtx = uni.createMapContext("map");
mapCtx.moveToLocation({
latitude: this.myLatitude,
longitude: this.myLongitude,
success: () => {
const timer = setTimeout(() => {
this.longitude = this.myLongitude,
this.latitude = this.myLatitude,
clearTimeout(timer);
//进行缩放,设置为16
this.scale = 16;
}, 300);
}
})
},
CSS:
.box {
position: relative;
width: 100%;
height: 70vh;
}
.home-icon {
border-radius: 10px;
position: absolute;
bottom: 20px;
left: 83%;
color: black;
background-color: #fff;
display: flex;
flex-direction: column;
align-items: center;
width: 55px;
height: 55px;
}
.targetIcon {
bottom: 100px;
}
.refresh {
top: 25px;
}
.u-btn {
width: 100% !important;
height: 100% !important;
border-radius: 50%;
}
简要叙述:首先在触发小程序onShow()生命周期时,我们会调用获取用户当前位置的方法getLocation(),使用到了wx.offLocationChange()、wx.stopLocationUpdate()、wx.startLocationUpdate()、wx.onLocationChange()四个api,这是其中一个的地址,他们四个配合使用刷新当前获取用户位置:uni.onLocationChange(FUNCTION CALLBACK) | uni-app官网。
在图中点击我的位置,将会回到用户当前位置并进行一个缩放,使用到了uni.createMapContext("map")、mapCtx.moveToLocation()等属性,官网地址是uni.createMapContext(mapId,this) | uni-app官网
有什么问题可以欢迎私信我