🌈个人主页:前端青山
🔖人终将被年少不可得之物困其一生
依旧青山,本期给大家带来Vue3+Ts+AntDesign-Vue组件+天地图组件的封装
示例图
首先,在index.html引入天地图资源,vue3选择v4版本
<script src="http://api.tianditu.gov.cn/api?v=4.0&tk=你的秘钥" type="text/javascript"></script>
- 使用
<BasicModal>
组件作为模态框基础样式,并通过@register
、@ok
、@cancel
等事件来注册、提交和取消选择点位操作。 - 组件内部使用天地图(Tianditu)进行地图展示和操作,包括初始化地图、点击地图获取坐标、根据地址搜索坐标等。
- 组件提供了一个搜索框,用户可以输入地址,通过点击搜索按钮来搜索对应的坐标,并在地图上标记。
- 组件可以接收初始的经纬度信息(通过
initialLongitude
和initialLatitude
两个props传递),并在地图上标记该位置。 - 组件内部使用了一些变量和函数来保存和操作地图、标记等信息,例如
mapInstance
、currentMaker
、longitude
、latitude
等。 - 组件提供了
success
和cancel
两个自定义事件,用于在选择点位成功或取消时通知父组件。
地图弹框示例代码
<template>
<div style="width: 100%" @click="show">
<slot></slot>
<!-- 弹框组件 -->
<BasicModal
width="1000px"
@register="registerModal"
@ok="submit"
@cancel="handleCancel"
destroy-on-close
:title="'请选择点位'"
>
<div class="mb-2">
<Input id="tipinput" v-model:value="searchValue" :placeholder="'请填写详细地址'"/>
<a-button type="primary" @click="search">搜索</a-button>
</div>
<!-- 使用天地图容器 -->
<div id="mapDiv" ref="wrapRef" style="width: 100%; height: 500px">
<div id="Tip" v-if="showCurrent">当前坐标:{
{longitude}}-{
{latitude}}</div>
</div>
</BasicModal>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref ,nextTick,toRefs } from 'vue';
import { BasicModal, useModal } from '/@/components/Modal';
import { Input, message } from 'ant-design-vue';
import GpsIcon from '/@/assets/images/gps.png';
const emits = defineEmits(['success', 'cancel']);
// 天地图相关数据绑定
const mapInstance = ref(null as any);
// 搜索区域内容
const searchValue = ref('');
// 变量保存Maker实例
const currentMaker = ref(null as any);
// 经度
const longitude = ref('');
// 纬度
const latitude = ref('');
// 判断当前坐标是否显示
const showCu