index.vue 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. import config from '@/config'
  10. const mapKey = config.mapKey;
  11. const QQMapWX = require('/static/sdk/qqmap-wx-jssdk.min.js')
  12. // 接收外部传入的地址
  13. const props = defineProps({
  14. address: {
  15. type: String,
  16. required: true,
  17. default: ''
  18. }
  19. });
  20. // 地图上下文
  21. const mapCtx = ref(null);
  22. const markers = ref([]);
  23. const mapData = ref({
  24. location: {
  25. lat: 0,
  26. lng: 0
  27. }
  28. })
  29. let qqmapsdk = null;
  30. onMounted(() => {
  31. console.log('mapKey-------------->',mapKey,QQMapWX);
  32. mapCtx.value = wx.createMapContext('wxMapId');
  33. qqmapsdk = new QQMapWX({
  34. key: mapKey
  35. });
  36. console.log('props',props.address);
  37. // 如果地址已经传入,立即进行地址转经纬度
  38. if (props.address) {
  39. geocodeAddress(props.address);
  40. }
  41. });
  42. // 监听地址变化
  43. watch(() => props.address, (newAddress) => {
  44. if (newAddress) {
  45. geocodeAddress(newAddress);
  46. }
  47. });
  48. // 地址转经纬度
  49. const geocodeAddress = (address) => {
  50. console.log('地址', address);
  51. qqmapsdk.geocoder({
  52. address: props.address,
  53. success: function (res) {
  54. console.log('初始化地图上下文', res);
  55. mapData.value = res.result;
  56. markers.value = [{
  57. latitude: res.result.location.lat,
  58. longitude: res.result.location.lng,
  59. id: 1,
  60. width: 20,
  61. height: 20,
  62. callout: {
  63. content: props.address,
  64. color: '#000000',
  65. fontSize: 12,
  66. borderRadius: 4,
  67. padding: 5,
  68. bgColor: '#ffffff',
  69. display: 'ALWAYS'
  70. }
  71. }];
  72. },
  73. fail: function (error) {
  74. console.error(error);
  75. },
  76. })
  77. };
  78. </script>
  79. <style lang="scss" scoped>
  80. map {
  81. width: 100%;
  82. height: 40vh;
  83. /* 确保地图占满整个视图高度 */
  84. }
  85. </style>