index.vue 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <template>
  2. <view>
  3. <map id="wxMapId" :longitude="mapData.location.lng" :latitude="mapData.location.lat" :markers="markers"
  4. style="width: 100%; height: 50vh;"></map>
  5. </view>
  6. </template>
  7. <script setup>
  8. import { ref, onMounted, watch } from 'vue';
  9. const QQMapWX = require('../../static/sdk/qqmap-wx-jssdk.js')
  10. // 接收外部传入的地址
  11. const props = defineProps({
  12. address: {
  13. type: String,
  14. required: true,
  15. default: ''
  16. }
  17. });
  18. // 地图上下文
  19. const mapCtx = ref(null);
  20. const markers = ref([]);
  21. const mapData = ref({
  22. location: {
  23. lat: 0,
  24. lng: 0
  25. }
  26. })
  27. let qqmapsdk = null;
  28. onMounted(() => {
  29. mapCtx.value = wx.createMapContext('wxMapId');
  30. qqmapsdk = new QQMapWX({
  31. key: 'KFEBZ-P2GKZ-A5PX4-7Q6Y7-KXOBF-XCB4C'
  32. });
  33. console.log('props',props.address);
  34. // 如果地址已经传入,立即进行地址转经纬度
  35. if (props.address) {
  36. geocodeAddress(props.address);
  37. }
  38. });
  39. // 监听地址变化
  40. watch(() => props.address, (newAddress) => {
  41. if (newAddress) {
  42. geocodeAddress(newAddress);
  43. }
  44. });
  45. // 地址转经纬度
  46. const geocodeAddress = (address) => {
  47. console.log('地址', address);
  48. qqmapsdk.geocoder({
  49. address: props.address,
  50. success: function (res) {
  51. console.log('初始化地图上下文', res);
  52. mapData.value = res.result;
  53. markers.value = [{ latitude: res.result.location.lat, longitude: res.result.location.lng,id: 1, }];
  54. },
  55. fail: function (error) {
  56. console.error(error);
  57. },
  58. })
  59. };
  60. </script>
  61. <style lang="scss" scoped>
  62. map {
  63. width: 100%;
  64. height: 40vh;
  65. /* 确保地图占满整个视图高度 */
  66. }
  67. </style>