<template>
    <view>
        <map id="wxMapId" :longitude="mapData.location.lng" :latitude="mapData.location.lat" :markers="markers"
            style="width: 100%; height: 50vh;"></map>
    </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
const QQMapWX = require('../../static/sdk/qqmap-wx-jssdk.js')
// 接收外部传入的地址
const props = defineProps({
    address: {
        type: String,
        required: true,
        default: '重庆市永川区中山路街道文昌路700号'
    }
});

// 地图上下文
const mapCtx = ref(null);
const markers = ref([]);

const mapData = ref({
    location: {
        lat: 0,
        lng: 0
    }
})
let qqmapsdk = null;

onMounted(() => {
    mapCtx.value = wx.createMapContext('wxMapId');

    qqmapsdk = new QQMapWX({
        key: 'KFEBZ-P2GKZ-A5PX4-7Q6Y7-KXOBF-XCB4C'
    });


    // 如果地址已经传入，立即进行地址转经纬度
    if (props.address) {
        geocodeAddress(props.address);
    }
});

// 监听地址变化
watch(() => props.address, (newAddress) => {
    if (newAddress) {
        geocodeAddress(newAddress);
    }
});

// 地址转经纬度
const geocodeAddress = (address) => {
    console.log('地址', address);

    qqmapsdk.geocoder({
        address: props.address,
        success: function (res) {
            console.log('初始化地图上下文', res);
            mapData.value = res.result;
            markers.value = [{ latitude: res.result.location.lat, longitude: res.result.location.lng,id: 1, }];
        },
        fail: function (error) {
            console.error(error);
        },
    })

};

</script>

<style lang="scss" scoped>
map {
    width: 100%;
    height: 40vh;
    /* 确保地图占满整个视图高度 */
}
</style>