index.vue 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <template>
  2. <view>
  3. <map id="wxMapId" :longitude="mapData.location.lng" :latitude="mapData.location.lat" :markers="markers"
  4. style="width: 100%; height: 40vh;"></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. mapCtx.value = wx.createMapContext('wxMapId');
  32. qqmapsdk = new QQMapWX({
  33. key: mapKey
  34. });
  35. // 如果地址已经传入,立即进行地址转经纬度
  36. if (props.address) {
  37. geocodeAddress(props.address);
  38. }
  39. });
  40. // 监听地址变化
  41. watch(() => props.address, (newAddress) => {
  42. if (newAddress) {
  43. geocodeAddress(newAddress);
  44. }
  45. });
  46. // 地址转经纬度
  47. const geocodeAddress = (address) => {
  48. qqmapsdk.geocoder({
  49. address: props.address,
  50. success: function (res) {
  51. mapData.value = res.result;
  52. markers.value = [{
  53. latitude: res.result.location.lat,
  54. longitude: res.result.location.lng,
  55. id: 1,
  56. width: 20,
  57. height: 20,
  58. callout: {
  59. content: props.address,
  60. color: '#000000',
  61. fontSize: 12,
  62. borderRadius: 4,
  63. padding: 5,
  64. bgColor: '#ffffff',
  65. display: 'ALWAYS'
  66. }
  67. }];
  68. },
  69. fail: function (error) {
  70. console.error(error);
  71. },
  72. })
  73. };
  74. </script>
  75. <style lang="scss" scoped>
  76. map {
  77. width: 100%;
  78. height: 40vh;
  79. /* 确保地图占满整个视图高度 */
  80. }
  81. </style>