从地理位置API返回值 [英] Returning Values from a geolocation API

查看:39
本文介绍了从地理位置API返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从地理位置api返回用户的经度和纬度,但到目前为止,当我尝试在功能之外使用它们时,我仍然收到错误消息.

I am trying to return the longitude and latitude of the user from the geolocation api but so far i keep getting errors when i try to use them outside the function.

我尝试使用函数中的值,它们可以工作,但是我似乎无法让它们在位置函数之外工作.我需要一种使位置"对象可供其他功能访问的方法.

I have tried using the values within the function and they work but i cannot seem to get them to work outside the position function. I need a way to make the "location" object accessible to other functions.

window.navigator.geolocation.getCurrentPosition(
  position => {
    const location = {
      lat:position.coords.latitude,
      long:position.coords.longitude
    }
    return location
  },
  (err)=>console.log(err),

);
console.log(location)

我希望将代码放入位置函数内的位置"对象内.请帮助

I expect to get the code inside the "location" object located within the position function.Please Help

推荐答案

HTML5 API getcurrentPosition是异步的,使用位置的最简单方法是使用回调函数,如下所示:

The HTML5 API getcurrentPosition is assync, the easiest way to use the location, is to use a callback function, like this:

window.navigator.geolocation.getCurrentPosition(
  position => {
    const location = {
      lat:position.coords.latitude,
      long:position.coords.longitude
    }
    showLocation(location); // <- Function that will use location data
  },
  (err)=>console.log(err),

);
function showLocation(location) {
    console.log(location);
    //other stuff    
}

此链接可以帮助您更好地理解: https://developer.mozilla.org/zh-CN/docs/Glossary/回调函数

this link can help to understand better: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

这篇关于从地理位置API返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆