求一个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>解决 无用评论 打赏 举报