【问题标题】:Geolocation Export lat and lng地理位置导出 lat 和 lng
【发布时间】:2018-07-19 20:09:28
【问题描述】:

我正在使用两个函数,第一个是使用地理定位 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()
    }
}

【问题讨论】:

    标签: javascript geolocation


    【解决方案1】:

    这是因为 getCurrentPosition 的工作方式与您预期的不同,因为它不会直接返回 latlong

    让我稍微重构一下代码。

    我会通过创建一个使用当前地理坐标解析的 Promise 来处理它,并在您的主 gpsLocation 函数中调用此 Promise。既然您使用的是async/await,我也会保持这种状态。 总的来说,它看起来像这样:

    //  a promise that resolves with geo coordinates
    const getPosition = (options) => {
      return new Promise(function (resolve, reject) {
        navigator.geolocation.getCurrentPosition(resolve, reject, options);
      });
    }
    
    const gpsLocation = async () => {
    
        try {
    
            // calling the promise and awaiting the position object
            const geolocationData = await getPosition({ enableHighAccuracy: true });
    
            // destructruing the coordinates from the object
            const {latitude: lat, longitude: lng} = geolocationData.coords;
    
            // creating promises for each api call
            const addressPromise = fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&result_type=administrative_area_level_4&key=0000000000000000`)
            const weatherDataPromise = fetch(`https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/0000000000000/${lat},${lng}?units=si&extend=hourly&exclude=flags&lang=el`);
    
            // wating for the promises to be resolved in parallel (rather than one after another)
            const [address, weatherData] = await Promise.all([addressPromise, weatherDataPromise]);
    
            return {
                address: address.json(),
                weatherData: weatherData.json()
            }
    
        } catch(e) {
            alert('Unable to fetch your location')
        }
    
    
    }
    

    下面是它的使用方法:

    (async () => {
    
        const { address, weather } = await gpsLocation();
    
        console.log(address);
        console.log(weather);
    
    })();
    

    让我知道以上适合你的作品;)

    【讨论】:

    • 谢谢 Leonid 很好的方法,也很好用。
    猜你喜欢
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多