求vue 腾讯地图获取当前位置和结束位置的距离

求一个vue 对接腾讯地图 获取当前位置 输入结束位置 并测算公里距离的dome


<template>
  <div>
    <button @click="getCurrentLocation">获取当前位置</button>
    <br>
    <input type="text" v-model="endLocation" placeholder="输入结束位置">
    <button @click="calculateDistance">计算距离</button>
    <br>
    <div v-if="distance">
      距离:{{ distance }}公里
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      endLocation: "",
      distance: null,
    };
  },
  methods: {
    getCurrentLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
          const { latitude, longitude } = position.coords;
          console.log("当前位置:", latitude, longitude);
        }, error => {
          console.log("无法获取当前位置:", error);
        });
      } else {
        console.log("不支持浏览器地理位置功能");
      }
    },
    calculateDistance() {
      if (this.endLocation) {
        const key = "你的腾讯地图API密钥";
        const url = `https://apis.map.qq.com/ws/distance/v1/?mode=driving&from=当前位置&to=${this.endLocation}&key=${key}`;
        
        fetch(url)
          .then(response => response.json())
          .then(data => {
            const distance = data.result.elements[0].distance / 1000; // 将距离转换为公里
            this.distance = distance.toFixed(2); // 保留两位小数
          })
          .catch(error => {
            console.log("计算距离失败:", error);
          });
      } else {
        console.log("请输入结束位置");
      }
    },
  },
};
</script>


<template>
  <div>
    <div>
      <h2>当前位置</h2>
      <p>{{ currentLocation }}</p>
    </div>
    <div>
      <h2>目的地</h2>
      <input type="text" v-model="destination" />
      <button @click="calculateDistance">计算距离</button>
    </div>
    <div>
      <h2>距离</h2>
      <p>{{ distance }} 公里</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentLocation: "",
      destination: "",
      distance: null,
      map: null,
      geolocation: null,
      driving: null,
    };
  },
  mounted() {
    // 加载腾讯地图API
    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = `https://map.qq.com/api/js?v=2.exp&key=YOUR_API_KEY&callback=initMap`;
    script.onerror = () => {
      console.error("加载腾讯地图API失败");
    };
    document.head.appendChild(script);
    // 初始化地图
    window.initMap = () => {
      this.map = new qq.maps.Map(document.getElementById("map"), {
        center: new qq.maps.LatLng(39.916527, 116.397128),
        zoom: 13,
      });
      this.geolocation = new qq.maps.Geolocation(
        "YOUR_API_KEY",
        "myapp"
      );
      this.driving = new qq.maps.DrivingService({
        complete: (result) => {
          if (!result) {
            console.error("计算距离失败");
            return;
          }
          const distance = result.detail.distance;
          this.distance = (distance / 1000).toFixed(2);
        },
      });
    };
    // 获取当前位置
    this.geolocation.getLocation((position) => {
      const latLng = new qq.maps.LatLng(
        position.lat,
        position.lng
      );
      const geocoder = new qq.maps.Geocoder({
        complete: (result) => {
          this.currentLocation = result.detail.address;
        },
      });
      geocoder.getAddress(latLng);
      this.map.setCenter(latLng);
      this.map.setZoom(16);
      const marker = new qq.maps.Marker({
        position: latLng,
        map: this.map,
      });
    });
  },
  methods: {
    calculateDistance() {
      if (!this.destination) {
        console.error("请输入目的地");
        return;
      }
      const geocoder = new qq.maps.Geocoder({
        complete: (result) => {
          const latLng = result.detail.location;
          this.driving.search(
            new qq.maps.LatLng(
              this.geolocation.position.lat,
              this.geolocation.position.lng
            ),
            latLng
          );
          const marker = new qq.maps.Marker({
            position: latLng,
            map: this.map,
          });
          this.map.setCenter(latLng);
          this.map.setZoom(16);
        },
      });
      geocoder.getLocation(this.destination);
    },
  },
};
</script>

<style>
#map {
  width: 100%;
  height: 300px;
}
</style>


在这个示例中,使用腾讯地图API的Geolocation和DrivingService服务来获取当前位置和计算距离。在mounted钩子函数中,首先加载腾讯地图API,然后初始化地图、Geolocation和DrivingService。使用Geolocation服务获取当前位置,并在地图上标记出来。

在calculateDistance方法中,使用Geocoder服务将输入的地址转换为经纬度,并使用DrivingService计算距离。在地图上标记出目的地,并将地图中心移动到目的地。