uniapp map实现打点和点击定位弹窗功能
时间: 2023-12-25 21:02:51 浏览: 99
1. 打点功能实现:
首先,在页面中引入uniapp的map组件:
```
<template>
<view class="map">
<unicomponent ref="uniMap" type="map" :latitude="latitude" :longitude="longitude" :markers="markers"></unicomponent>
</view>
</template>
```
然后在script中定义data数据:
```
export default {
data() {
return {
latitude: 0,
longitude: 0,
markers: []
}
}
}
```
接着,在mounted生命周期中调用getCenterLocation方法获取当前地图中心点的经纬度,并将其赋值给data中的latitude和longitude:
```
mounted() {
this.$refs.uniMap.getCenterLocation({
success: (res) => {
this.latitude = res.latitude;
this.longitude = res.longitude;
}
})
}
```
接下来,我们可以通过uniapp的map组件的bindtap事件来实现打点功能。首先,在data中定义一个变量count,用于计算点击地图的次数:
```
data() {
return {
latitude: 0,
longitude: 0,
markers: [],
count: 0
}
}
```
然后,在map组件上绑定bindtap事件:
```
<unicomponent ref="uniMap" type="map" :latitude="latitude" :longitude="longitude" :markers="markers" @tap="onTap"></unicomponent>
```
最后,在onTap方法中实现打点功能:
```
onTap(e) {
this.count++;
const marker = {
id: this.count,
latitude: e.detail.latitude,
longitude: e.detail.longitude,
title: `点${this.count}`,
iconPath: '/static/images/marker.png',
width: 40,
height: 40
}
this.markers.push(marker);
}
```
2. 点击定位弹窗功能实现:
首先,在页面中引入uniapp的button组件用于触发定位:
```
<template>
<view class="map">
<view class="button" @click="getLocation">定位</view>
<unicomponent ref="uniMap" type="map" :latitude="latitude" :longitude="longitude" :markers="markers"></unicomponent>
</view>
</template>
```
然后,在script中实现getLocation方法:
```
methods: {
getLocation() {
uni.getLocation({
type: 'gcj02',
success: (res) => {
this.latitude = res.latitude;
this.longitude = res.longitude;
this.showPopup();
}
})
},
showPopup() {
uni.showModal({
title: '当前位置',
content: `经度:${this.longitude}\n纬度:${this.latitude}`
})
}
}
```
getLocation方法中调用uniapp的getLocation方法获取当前位置的经纬度,并将其赋值给data中的latitude和longitude。接着,调用showPopup方法弹出当前位置的经纬度。
至此,我们就完成了uniapp中map组件的打点和点击定位弹窗功能的实现。