You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3使用@vueuse/core的useGeolocation获坐标返回Infinity问题排查

问题成因
  • 地理定位是异步操作,onMounted钩子执行时,浏览器还没完成位置获取,此时coords.value是useGeolocation预设的初始占位值(为Infinity),并非真实坐标。
  • 仅在onMounted中一次性读取coords,没有监听其后续变化,导致无法捕获定位完成后的真实数据。
解决方法

1. 监听coords的变化

使用Vue的watch或watchEffect监听coords,当定位成功、坐标更新时再赋值给form:

<script setup>
import { ref, watch } from "vue";
import { useGeolocation } from "@vueuse/core";

const { coords, error } = useGeolocation();
const form = ref({ coords: null });

// 监听coords变化,获取真实坐标
watch(coords, (newCoords) => {
  // 排除初始的Infinity无效值
  if (!isNaN(newCoords.latitude) && !isNaN(newCoords.longitude)) {
    form.value.coords = {
      latitude: newCoords.latitude,
      longitude: newCoords.longitude
    };
    console.log("真实坐标:", newCoords);
  }
}, { deep: true });

// 监听定位错误
watch(error, (err) => {
  if (err) {
    console.error("定位失败:", err.message);
  }
});
</script>

2. 利用locatedAt判断定位状态

useGeolocation返回的locatedAt会在定位成功后更新为时间戳,可通过它判断是否已获取到有效坐标:

<script setup>
import { ref, watch } from "vue";
import { useGeolocation } from "@vueuse/core";

const { coords, locatedAt, error } = useGeolocation();
const form = ref({ coords: null });

watch(locatedAt, (timestamp) => {
  if (timestamp) {
    form.value.coords = {
      latitude: coords.value.latitude,
      longitude: coords.value.longitude
    };
    console.log("定位完成时间:", new Date(timestamp));
  }
});

// 错误处理
watch(error, (err) => err && console.error("定位出错:", err));
</script>

3. 处理权限场景

确保用户已授权浏览器获取位置信息:

  • 浏览器会弹出授权请求,需用户允许;
  • 如果用户拒绝,error会返回权限相关错误,需在代码中提示用户开启权限。

内容的提问来源于stack exchange,提问作者Leslie Joe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 09:27:03