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

React PWA中封装getCurrentPosition函数无法返回位置值是什么原因

问题原因分析

你遇到的问题本质是地理定位API是异步操作,无法像普通同步函数一样直接返回执行结果:

  • 非Promise版本的问题:navigator.geolocation.getCurrentPosition 接收的success回调是定位完成后才会异步执行,你在success函数里的return只会把值返回给回调的调用方,不会传递到外层的getLocation函数。同时getLocation本身没有顶层return语句,默认返回undefined,所以外部调用拿到的就是undefined。
  • Promise版本的问题:你封装的getGeoLocation没有把Promise链返回出去,只是内部执行了.then逻辑,函数本身没有返回值,自然外部拿不到结果。即使加了return返回Promise,也不能直接同步赋值拿到结果,必须通过.then或者await获取异步返回值。
正确封装与调用实现

封装代码(getGeoLocation.ts)

export default function getGeoLocation (): Promise<{latitude: number, longitude: number}> {
    return new Promise((resolve, reject) => {
        const options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };
        function success (position: GeolocationPosition) {
            resolve({
                latitude: position.coords.latitude, 
                longitude: position.coords.longitude
            })
        }
        function error(err: GeolocationPositionError) {
            console.warn(`ERROR(${err.code}): ${err.message}`);
            reject(err)
        }
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success, error, options)
        } else {
            reject("your browser doesn't support geolocation API")
        }
    })
}

调用方式

方式1:.then 链式调用

import getGeoLocation from '../utils/getGeoLocation';

getGeoLocation()
    .then(location => {
        console.log(location); // 此处可拿到正确的位置信息
        // 所有依赖位置的后续逻辑都要写在这个回调内
    })
    .catch(err => {
        // 处理定位失败的逻辑
        console.error('定位失败:', err)
    })

方式2:async/await 调用(语法更简洁)

import getGeoLocation from '../utils/getGeoLocation';

// 调用逻辑需要放在async标记的函数内
const getLocationHandler = async () => {
    try {
        const location = await getGeoLocation();
        console.log(location); // 此处可拿到正确的位置信息
        // 所有依赖位置的后续逻辑都可以写在try块内
    } catch (err) {
        console.error('定位失败:', err)
    }
}

// 执行调用函数
getLocationHandler();

内容的提问来源于stack exchange,提问作者Raissa Correia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 08:36:07