index.vue 8.73 KB
<template>
  <div style="width: 100%;">
    <div id="mapContainer" class="map"></div>
    <div class="search-box" v-if="isx">
      <input v-model="searchQuery" placeholder="输入地址进行搜索" />
      <div style="box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);display: flex;align-items: center;background: #fff;padding: 0 20px;border-radius: 5px;overflow: hidden;margin-left: 10px;">
        <i class="el-icon-search" style="margin-right: 10px;color: #3F9B6A;"></i>
        <button type="button" @click="searchLocation">搜索</button>
      </div>
    </div>
    <div v-if="searchResults.length > 0" class="search-results">
      <ul>
        <li v-for="(result, index) in searchResults" :key="index" @click="selectResult(result)">
          {{ result.title }}
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
  export default {
    name: 'TencentMap',
    props: {
      lat: {
        type: Number,
        default: 30.67
      },
      lng: {
        type: Number,
        default: 104.06
      },
      isonloed: {
        type: Boolean,
        default: false
      },
      isx: {
        type: Boolean,
        default: true
      },
      message: {
        type: String,
        default: ''
      },
    },
    data() {
      return {
        map: null,
        marker: null,
        address: '',
        searchQuery: '', // 搜索查询
        searchResults: [], // 搜索结果列表

      };
    },
    mounted() {
      // 初始化地图
      let that = this;
      // 延迟2秒执行,避免地图加载失败
      setTimeout(() => {
        that.initMap();
      }, 2000);
    },
    methods: {
      // 选择某一条搜索结果
      selectResult(result) {

        console.error('====')
        let lat = result.location.lat;
        let lng = result.location.lng;
        
        //修改点标记的位置
        this.marker.updateGeometries([
          {
            "styleId":"myStyle",
            "id": "1",
            "position": new TMap.LatLng(lat, lng),
          }
        ])

        // const latLng = new TMap.maps.LatLng(result.location.lat, result.location.lng);

        // // 移动地图中心到选择的位置
        // this.map.setCenter(latLng);

        // // 更新标记位置
        // this.marker.setPosition(latLng);

        // 获取地址信息
        this.getAreaCode(result.location.lat, result.location.lng);

        
      },
      searchLocation() {
        let that = this
        if (!this.searchQuery) {
          this.$message.error('请输入搜索地址');
          return;
        }

        // 使用腾讯地图的搜索服务
        this.$jsonp("https://apis.map.qq.com/ws/place/v1/search", {
          keyword: this.searchQuery,
          key: 'PGRBZ-Z3FRJ-DTYFB-XNX4X-DC6HZ-MCFYU', // 使用你的腾讯地图API key
          output: "jsonp",
          boundary: 'nearby(' + that.lat + ',' + that.lng + ',1000,1)'
        }).then((res) => {
          console.error(res)
          if (res.status === 0 && res.data.length > 0) {
            this.searchResults = res.data; // 存储搜索结果
          } else {
            this.$message.error('未找到相关地址');
            this.searchResults = []; // 清空搜索结果
          }
        }).catch(err => {
          this.$message.error("搜索失败");
          console.error(err);
        });
      },
      initMap() {
        if (this.isx) {
        
        } else {
          this.lat = Number(this.message.split(',')[0])
          this.lng = Number(this.message.split(',')[1])
        }
        // 将经纬度转换为腾讯地图的LatLng对象
        const centerLatLng = new TMap.LatLng(this.lat, this.lng);

        this.map = new TMap.Map(document.getElementById("mapContainer"), {
          center: centerLatLng,
          zoom: 13,
          mapStyleId: 'style1'
        });

        // 创建标记
        if (this.isonloed) {
          this.marker = new TMap.MultiMarker({
            map: this.map,  //指定地图容器
            //点标记数据数组
            geometries: [
              {
                "styleId":"myStyle",
                "id": "1",
                "position": new TMap.LatLng(this.lat,this.lng),
              }
            ]
          });
        } else {
          this.marker = new TMap.MultiMarker({
            map: this.map
          });
        }
        if (this.isx) {
          // TMap.maps.event.addListener(this.map, 'click', this.onMapClick);

          this.map.on("click",this.onMapClick)
        } else {
          // const centerLatLng1 = new TMap.maps.LatLng(this.message.split(',')[0], this.message.split(',')[1]);
          // console.error(this.message)
          // this.marker = new TMap.maps.Marker({
          //   position: centerLatLng1,
          //   map: this.map
          // });
          this.marker = new TMap.MultiMarker({
            map: this.map,  //指定地图容器
            //点标记数据数组
            geometries: [
              {
                "styleId":"myStyle",
                "id": "1",
                "position": new TMap.LatLng(Number(this.message.split(',')[0]), Number(this.message.split(',')[1])),
              }
            ]
          });
        }

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

        // 添加地图点击事件监听器


        // // 获取地址信息
        // this.getAreaCode(this.lat, this.lng);
      },
      onMarkerClick() {
        alert('您点击了标记点');
      },
      onMapClick(evt) {
        console.error('====')
        let lat = evt.latLng.getLat().toFixed(6);
        let lng = evt.latLng.getLng().toFixed(6);
        
        //修改点标记的位置
        this.marker.updateGeometries([
          {
            "styleId":"myStyle",
            "id": "1",
            "position": new TMap.LatLng(lat, lng),
          }
        ])
        
        // // 回显经纬度
        // _this.$emit('PositionDegrees', {lng, lat})
        // // 获取点击位置的经纬度
        // const newLatLng = event.latLng;

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


        // // 获取新的地址信息

      },
      getAreaCode(lat, lng) {
        this.searchQuery = ''
        // 清空搜索结果
        this.searchResults = [];
        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: Number(lat),
              lng: Number(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;
  }

  .search-box {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    /* background: #fff; */
    /* padding: 10px; */
    /* border-radius: 5px; */
    /* box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); */
    /* width: 280px; */
    display: flex;
    justify-content: space-between;
  }

  .search-box input {
    /* padding: 5px; */
    padding: 15px 8px;
    margin-right: 5px;
    font-size: 10px;
    box-sizing: border-box;
    border-radius: 5px;
    border: 1px solid #eee;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    width: 200px;
  }

  .search-box button {
    padding: 15px 0;
    background-color: #fff;
    /* color: #fff; */
    border: none;
    border-radius: 3px;
    cursor: pointer;
    height: 100%;
    box-sizing: border-box;
    font-size: 10px;
    color: -internal-light-dark(black, white);
  }

  .search-box button:hover {
    background-color: #fff;
  }

  .search-results {
    position: absolute;
    top: 60px;
    left: 10px;
    z-index: 1000;
    background: #fff;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    max-height: 200px;
    overflow-y: auto;
    width: 280px;
    
  }
  .search-results::-webkit-scrollbar {
    display: none; /* 隐藏滚动条 */
  }
  .search-results ul {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .search-results li {
    padding: 5px;
    cursor: pointer;
  }

  .search-results li:hover {
    background-color: #f0f0f0;
  }
</style>