先附上子組件的代碼(引入的地圖js文件key是官方示例中給的key,實際開發需要換成自己的):
<template>
<div>
<van-button type="success">獲取定位</van-button>
若發現位置不准可放大地圖進行點擊切換位置操作
</div>
<div id="TxMap"></div>
</template>
<script setup lang="ts">
import { onMounted, toRefs, ref, watch } from 'vue'
import { Toast } from 'vant'
const props = defineProps({
lat: Number,
lng: Number,
shopName: String
})
const emit = defineEmits([
'update',
])
const { lat, lng, shopName } = toRefs(props)
let mapFn
const initMap = () => {
// 定義地圖中心點坐標
let center = new window.TMap.LatLng(lat.value, lng.value)
// 定義map變量,調用 TMap.Map() 構造函數創建地圖
mapFn = new window.TMap.Map('TxMap', {
center: center, // 設置地圖中心點坐標
zoom: 17, // 設置地圖縮放級別
viewMode: '2D', // 設置2D模式
showControl: true, // 去掉控件
})
let markerLayer = new window.TMap.MultiMarker({
id: 'marker-layer',
map: mapFn, // 顯示Marker圖層的底圖
styles: {
small: new window.TMap.MarkerStyle({
// 點標注的相關樣式
width: 34, // 寬度
height: 46, // 高度
anchor: { x: 17, y: 23 }, // 標注點圖片的錨點位置
src: 'https://mapapi.qq.com/web/lbs/visualizationApi/demo/img/small.png', // 標注點圖片url或base64地址
color: '#B45F04', // 標注點文本顏色
size: 20, // 標注點文本文字大小
direction: 'top', // 標注點文本文字相對於標注點圖片的方位
offset: { x: 0, y: 0 }, // 標注點文本文字基於direction方位的偏移屬性
strokeColor: '#fff', // 標注點文本描邊顏色
strokeWidth: 2, // 標注點文本描邊寬度
}),
},
geometries: [
{
id: 'shop',
styleId: 'small', // 對應中的樣式id
position: center, // 標注點位置
content: shopName.value, // 標注點文本
},
],
})
mapFn.on('click', evt => {
const evtModel = {
lat: evt.latLng.getLat().toFixed(6),
lng: evt.latLng.getLng().toFixed(6),
}
emit('update', evtModel)
markerLayer.updateGeometries({
id: 'shop',
position: evt.latLng,
styleId: 'small',
content: shopName.value,
})
})
mapFn.on('idle', () => {
watch(() => shopName.value, (newVal, oldVal) => {
markerLayer.updateGeometries({
id: 'shop',
position: new window.TMap.LatLng(lat.value, lng.value),
styleId: 'small',
content: shopName.value,
})
})
})
}
const count = ref(123456)
defineExpose({
count
})
onMounted(() => {
const mapScript = document.createElement('script')
mapScript.type = 'text/javascript'
mapScript.src = 'https://map.qq.com/api/gljs?v=1.exp&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77'
document.body.appendChild(mapScript)
mapScript.onload = () => {
//加載完成后初始化地圖
initMap()
}
})
</script>
<style lang="less" scoped>
#TxMap {
width: 100%;
height: 100vw;
}
</style>
父組件頁面引入:
import TxMap from '../../components/txmap/index.vue'
<template>
<TxMap ref="hello" :lat="storeModel.Latitude" :lng="storeModel.Longitude" :shop-name="storeModel.Name" @update="updateMap" />
</template>
綁定經緯度和顯示內容即可,通過點擊地圖從子組件獲取的經緯度emit給父組件雙向綁定
const updateMap = (evtModel: object) => { storeModel.Latitude = parseFloat(evtModel.lat) storeModel.Longitude = parseFloat(evtModel.lng) }
