Javascript 地理定位出口lat和lng

Javascript 地理定位出口lat和lng,javascript,geolocation,Javascript,Geolocation,我使用两个函数,第一个是使用地理定位API,我想返回lat和lng 在第二个函数中,我想用这个坐标获取一些数据 但我无法在第一个函数中正确导出它 我得到geolocationData()不是一个函数 这是我的密码 const geolocationData = () => { return navigator.geolocation.getCurrentPosition((position) => { return position }, () =&g

我使用两个函数,第一个是使用地理定位API,我想返回lat和lng

在第二个函数中,我想用这个坐标获取一些数据 但我无法在第一个函数中正确导出它

我得到geolocationData()不是一个函数

这是我的密码

const geolocationData = () => {
    return navigator.geolocation.getCurrentPosition((position) => {
        return position
    }, () => {
        alert('Unable to fetch your location')
    }, { enableHighAccuracy: true })
}

const gpsLocation = async () => {

    const lat = geolocationData().position.coords.latitude
    const lng = geolocationData().position.coords.longitude

    const address = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&result_type=administrative_area_level_4&key=0000000000000000`)
    const weatherData = await fetch(`https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/0000000000000/${lat},${lng}?units=si&extend=hourly&exclude=flags&lang=el`)

    return {
        address: address.json(),
        weatherData: weatherData.json()
    }
}
这是因为它的工作方式与您预期的不同,因为它不会直接返回
lat
long

让我稍微重构一下代码

我将通过创建一个与当前地理坐标解析的承诺来实现它,并在主
gpsLocation
函数中调用此承诺。因为您使用的是
async/await
,所以我也会这样保存它。 总的来说,它看起来像这样:

//用地理坐标解析的承诺
const getPosition=(选项)=>{
返回新承诺(功能(解决、拒绝){
navigator.geolocation.getCurrentPosition(解析、拒绝、选项);
});
}
const gpsLocation=async()=>{
试一试{
//调用promise并等待position对象
const geolocationData=await getPosition({enableHighAccurance:true});
//从对象中销毁坐标
常数{纬度:纬度,经度:lng}=geolocationData.coords;
//为每个api调用创建承诺
const addressPromise=fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat}、${lng}&result\u type=administrative\u area\u level\u 4&key=0000000000000000`)
const weatherDataPromise=fetch(`https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/0000000000000/${lat},${lng}?单位=si&extend=hourly&exclude=flags&lang=el`);
//等待承诺并行解决(而不是一个接一个)
const[address,weatherData]=等待承诺。全部([addressPromise,weatherDataPromise]);
返回{
地址:address.json(),
weatherData:weatherData.json()
}
}捕获(e){
警报('无法获取您的位置')
}
}
下面是它的使用方法:

(async () => {

    const { address, weather } = await gpsLocation();

    console.log(address);
    console.log(weather);

})();

让我知道你的上述作品;)

谢谢你,莱昂尼德,这是一个很好的方法。