index.vue 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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: '重庆市永川区中山路街道文昌路700号'
  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. // 如果地址已经传入,立即进行地址转经纬度
  34. if (props.address) {
  35. geocodeAddress(props.address);
  36. }
  37. });
  38. // 监听地址变化
  39. watch(() => props.address, (newAddress) => {
  40. if (newAddress) {
  41. geocodeAddress(newAddress);
  42. }
  43. });
  44. // 地址转经纬度
  45. const geocodeAddress = (address) => {
  46. console.log('地址', address);
  47. qqmapsdk.geocoder({
  48. address: props.address,
  49. success: function (res) {
  50. console.log('初始化地图上下文', res);
  51. mapData.value = res.result;
  52. markers.value = [{ latitude: res.result.location.lat, longitude: res.result.location.lng,id: 1, }];
  53. },
  54. fail: function (error) {
  55. console.error(error);
  56. },
  57. })
  58. };
  59. </script>
  60. <style lang="scss" scoped>
  61. map {
  62. width: 100%;
  63. height: 40vh;
  64. /* 确保地图占满整个视图高度 */
  65. }
  66. </style>