index.vue 3.02 KB
<template>
  <div style="position: relative;width: 100%;">
    <div id="mapContainer" class="map"></div>
    <!-- <div id="addressInfo" class="address-info">
      <p v-if="address">地址: {{ address }}</p>
      <p v-if="center">地址: {{ lat }}</p>
      <p v-if="center">地址: {{ lng }}</p>
      <p v-else>加载中...</p>
    </div> -->
  </div>
</template>

<script>
  export default {
    name: 'TencentMap',
    props: {
      lat: {
        type: Number,
        default: 30.67
      },
      lng: {
        type: Number,
        default: 104.06
      },
    },
    data() {
      return {
        map: null,
        marker: null,
        address: ''
      };
    },
    mounted() {
      // 初始化地图
      this.initMap();
    },
    methods: {
      initMap() {
        // 将经纬度转换为腾讯地图的LatLng对象
        const centerLatLng = new qq.maps.LatLng(this.lat, this.lng);

        // 创建地图实例
        this.map = new qq.maps.Map(document.getElementById('mapContainer'), {
          center: centerLatLng,
          zoom: 13
        });
        // 创建标记
        this.marker = new qq.maps.Marker({
          position: centerLatLng,
          map: this.map
        });

        // 添加点击事件监听器
        // qq.maps.event.addListener(this.marker, 'click', this.onMarkerClick);

        // 添加地图点击事件监听器
        qq.maps.event.addListener(this.map, 'click', this.onMapClick);

        // // 获取地址信息
        // this.getAreaCode(this.lat, this.lng);
      },
      onMarkerClick() {
        alert('您点击了标记点');
      },
      onMapClick(event) {
        // 获取点击位置的经纬度
        const newLatLng = event.latLng;

        // 更新标记位置
        this.marker.setPosition(newLatLng);
        this.getAreaCode(newLatLng.getLat(), newLatLng.getLng());
        // 更新父组件中的经纬度


        // 获取新的地址信息

      },
      getAreaCode(lat, lng) {
        let that = this;
        //这里可以直接this.$jsonp地址传入你的经纬度;
        that.$jsonp("https://apis.map.qq.com/ws/geocoder/v1/?", {
          location: `${lat},${lng}`, // 经纬度
          key: 'PGRBZ-Z3FRJ-DTYFB-XNX4X-DC6HZ-MCFYU', //这里就是要开启那个service不然会报错让你开启
          output: "jsonp", // output必须jsonp 不然会超时
        }).then((res) => {
          if (res.message == 'Success') {
            console.log(res);
            that.address = res.result.address
            that.$emit('updatecenter', {
              lat: lat,
              lng: lng,
              address: that.address
            });
          } else {
            this.$message.error(res.message)

          }
        }).catch(err => {
          this.$message.error("获取城市编码失败")
          console.error(err)
        })
      }
    }
  }
</script>

<style scoped>
  .map {
    width: 100%;
    height: 300px;
  }

  .address-info {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 999999;
    background: #fff;
  }
</style>