丁崽 2023-05-28 23:49 采纳率: 53.8%
浏览 36
已结题

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

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

  • 写回答

2条回答 默认 最新

  • 啊啊啊啊啊威 2023-05-29 05:18
    关注
    
    <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>
    
    
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月30日
  • 创建了问题 5月28日