安装依赖
npm install vue-qqmap
组件名MapChoose.vue,组件内容:
<template>
<div :key="domKey">
<el-button @click="selectCoordinate" type="primary">位置选择</el-button>
<el-dialog
title="位置选择"
@close="cancelMap"
v-model="codeVisible"
width="900px"
>
<div class="flex flex-col justify-between">
<vqqmap v-model="location" @update="mapChange" :options="options" />
<div
class="dialog-footer"
style="padding-top: 50px; display: flex; justify-content: right"
>
<div>
<el-button @click="cancelMap">取 消</el-button>
<el-button type="primary" @click="handelOk">确 定</el-button>
</div>
</div>
</div>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import vqqmap from "vue-qqmap";
const domKey = ref(0);
const formData = reactive<object>({});
const emit = defineEmits(["getLocation"]);
// 地图
const location = reactive({
lat: "",
lng: "",
address: "",
});
const props = defineProps({
atLocation: {
type: String,
default: "31.1269,104.3978",
},
address: {
type: String,
default: "德阳市人民政府",
},
});
watch(
[() => props.atLocation, () => props.address],
([newVal1, newVal2], [oldVal1, oldVal2]) => {
if (newVal1) {
location.lat = newVal1.split(",")[0];
location.lng = newVal1.split(",")[1];
location.address = newVal2;
} else {
location.latitude = "";
location.longitude = "";
location.address = "";
return "";
}
},
{ immediate: true, deep: true }
);
const options = reactive({ key: "xxxx" });
const codeVisible = ref(false);
// 弹出地图弹框
const selectCoordinate = () => {
codeVisible.value = true;
formData.latitude = location.lat;
formData.longitude = location.lng;
formData.address = location.address;
};
// 地图更换
const mapChange = (data) => {
formData.latitude = data.lat;
formData.longitude = data.lng;
formData.address = data.address;
};
const cancelMap = () => {
codeVisible.value = false;
emit("getLocation", formData);
domKey.value = domKey.value + 1;
};
const handelOk = () => {
codeVisible.value = false;
emit("getLocation", formData);
domKey.value = domKey.value + 1;
};
</script>
页面使用
省略引用组件步骤
<MapChoose
:atLocation="formData.placeLoc"
:address="formData.placeName"
@get-location="getLocation"
style="margin-left: 10px"/>
const formData = reactive<object>({
placeLoc : '',
placeName : '',
});
const getLocation = (obj) => {// 组件返回的经纬度和地址名称
formData.placeLoc = obj.latitude + "," + obj.longitude;
formData.placeName = obj.address;
};