简体   繁体   English

地理位置导出纬度和经度

[英]Geolocation Export lat and lng

I am using two functions the first is using the geolocation API and i want to return the lat and lng 我正在使用两个函数,第一个是使用地理位置API,我想返回lat和lng

In the second function i want to fetch some data with this coordinates but i can't export it properly on first function. 在第二个函数中,我想使用此坐标来获取一些数据,但无法在第一个函数中正确导出它。

I get geolocationData() is not a function. 我得到geolocationData()不是函数。

Here is my code 这是我的代码

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()
    }
}

That is because getCurrentPosition works in a different way than you anticipate it to, as it does not return lat and long directly. 这是因为getCurrentPosition工作方式与您预期的不同,因为它不会直接返回latlong

Let me refactor that code a little bit. 让我重构一下代码。

I would approach it by creating a promise which resolves with current geo coordinates and call this promise in your main gpsLocation function. 我将通过创建一个可以解决当前地理坐标的承诺并在您的主要gpsLocation函数中调用此承诺来实现这一gpsLocation Since you are using async/await , I'll also keep it like that. 由于您使用的是async/await ,因此我也将其保持不变。 Overall, it would look something like this: 总的来说,它看起来像这样:

//  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')
    }


}

And here is how it could be used: 这是如何使用它:

(async () => {

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

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

})();

Let me know of the above works for you ;) 让我知道以上适用于您的作品;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 地理位置和计算当前经纬度到另一经纬度的距离 - Geolocation and calculating distance from current lat/lng to another lat/lng Google Maps API地理位置+纬度/经度 - Google Maps API Geolocation + Lat / Lng 谷歌地图 - 在地理定位通过 lat/lng 变量之前加载地图 - Google Map - map loading before geolocation passes lat/lng variable 隐藏的“ lat”和“ lng”字段未删除,因此我的脚本仍在搜索来自错误地理位置的lat和lng结果 - The hidden 'lat' and 'lng' fields were not removed and so my script was still searching for the lat and lng results from the incorrect geolocation 如何在 React 中将地理定位经纬度从一个函数传递到另一个函数的`ll` 属性? - How to pass a geolocation lat lng from a function to another's `ll` property in React? 确定边界中的纬度/经度 - Determine if Lat/Lng in Bounds 获取用户的地理位置,应用程序显示纬度和经纬度,但无法获取用户所在城市名称的反向地理编码 - getting user's geolocation, the app displays the lat and lng but can't get the reverse geocode for the city name of the user's 带纬度/经度输入的拖动点 - Drag points with Lat/Lng inputs 相对于图像的单张lng / lat - Leaflet lng/lat relative to image 根据地址获取经度 - Get the lat,lng base on address
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM