uniapp 自定义地图组件(根据经纬度展示地图地理位置)
目录
一、定义组件(pages/compoent/diy/mapDiy.vue)
二、父页面引入子组件
一、定义组件(pages/compoent/diy/mapDiy.vue)
<template>
<view class="diy-map" :style="{padding: paddingTop + ' ' + paddingLeft, background: showStyle.background, borderRadius: itemBorderRadius}">
<map class="map" :latitude="showParams.latitude" :longitude="showParams.longitude" :style="{height: height}" @click="onClick"></map>
</view>
</template>
<script>
export default {
name: 'mapDiy',
props: ['showStyle', 'showParams'],
computed: {
itemBorderRadius() {
return uni.upx2px(this.showStyle.itemBorderRadius * 2) + 'px';
},
height() {
return uni.upx2px(this.showStyle.height * 2) + 'px';
},
paddingTop() {
return uni.upx2px(this.showStyle.paddingTop * 2) + 'px';
},
paddingLeft() {
return uni.upx2px(this.showStyle.paddingLeft * 2) + 'px';
},
},
methods: {
// 点击事件
onClick() {
uni.openLocation({
latitude: parseFloat(this.showParams.latitude),
longitude: parseFloat(this.showParams.longitude),
});
}
}
}
</script>
<style lang="scss">
.diy-map .map {
width: 100%;
}
</style>
二、父页面引入子组件
- 写一个按钮获取当前地理位置
<!-- 获取当前位置按钮 -->
<button @click="getCurrentLocation">获取当前位置</button>
<!-- 地图展示区域 -->
<map-diy v-if="showMap" :showParams="mapParams" :showStyle="mapStyle"></map-diy>
- 引入组件
import mapDiy from "@/pages/component/diy/mapDiy.vue";
export default {
components: {
articleItem,
mapDiy,
},
data() {
return {
showMap: false, // 是否显示地图
mapParams: { latitude: '', longitude: '' }, // 地图的经纬度参数
mapStyle: { height: 300, background: '#fff', paddingTop: 10,itemBorderRadius: 8 } // 地图样式
};
},
methods: {
// 获取当前位置信息并显示地图
getCurrentLocation() {
wx.getLocation({
type: 'wgs84', // 获取GPS定位的经纬度
success: (res) => {
const latitude = res.latitude;
const longitude = res.longitude;
// 更新地图参数并显示地图
this.mapParams = { latitude, longitude };
this.showMap = true; // 显示地图
},
fail: (error) => {
wx.showToast({
title: '无法获取位置,请检查权限',
icon: 'none'
});
}
});
},